React Component
React Component
In React, a component is essentially a reusable piece of code that encapsulates a specific piece of functionality or user interface element. Components are the building blocks of React applications, allowing developers to create complex user interfaces by composing smaller, modular pieces.
Suppose we want to create a component for displaying a basic button.import React from 'react'; // Functional Component const Button = (props) => { return ( <button onClick={props.onClickEventProp}> {props.labelProp} </button> ); } export default Button;
Now, let's use this
Button
component inApp
parent component,import React from 'react'; import Button from './Button'; const App = () => { const handleClick = () => { alert('Button clicked!'); }; return ( <div> <h1>My App</h1> <Button onClickEventProp={handleClick} labelProp="Click Me" /> </div> ); } export default App;
Nesting Component
Nesting components in React is a fundamental concept that allows you to compose complex user interfaces by breaking them down into smaller, reusable pieces. Let's illustrate this with an example of nesting components to create a simple webpage layout.
Suppose we want to create a webpage layout consisting of a header, a main content area, and a footer. We can achieve this by creating separate components for each section and then nesting them within a parent component representing the entire webpage layout.
iii) Now, let's create the parent component representing the entire webpage layout and nest theHeader
andFooter
components within it,import React from 'react'; import Header from './Header'; import Footer from './Footer'; const App = () => { return ( <div> <Header /> <main> <h2>Welcome to My Website</h2> <p>This is the main content area of the website.</p> </main> <Footer /> </div> ); } export default App;
We import the
Header
andFooter
components into theApp
component.
Inside theApp
component, we nest theHeader
andFooter
components within<Header />
and<Footer />
tags respectively.Component Tree
In React, the component tree refers to the hierarchical structure formed by nesting components within one another. It represents the relationship between parent and child components in a React application.
i) Root Component
At the top of the component tree is the root component, typically rendered usingReactDOM.render()
in the entry point of your application (e.g.,index.js
).
The root component can contain one or more child components, forming the beginning of the component hierarchy.
ii) Parent and Child Components
Components in React can be composed by nesting them within one another, creating a parent-child relationship.The parent component is the one that contains and renders child components within its JSX.
Child components are nested inside parent components and can themselves be parents to other components.
iv) Hierarchical StructureAs components are nested within one another, they form a hierarchical structure resembling a tree.
Each component can have multiple child components, and each child component can have its own children, forming a branching structure.
v) Data FlowData and props flow down the component tree from parent to child components. Parent components can pass data and props to their children, which they can then use to render their own UI or pass down further to their own children.
Events and state changes can also flow up the component tree from child to parent components using callbacks passed as props.
vi) Re-renderingWhen the state or props of a component change, React automatically re-renders that component and its children. This process is efficient because React only updates the parts of the component tree that have changed, rather than re-rendering the entire tree.
Understanding the component tree is crucial for building React applications efficiently. It helps you structure your application's UI in a modular and reusable way, breaking it down into smaller, manageable components. Additionally, it facilitates data flow and communication between components, enabling you to build dynamic and interactive user interfaces.Advantages of Component
Components are one of the core building blocks of React applications, and they offer several advantages,
i) Modularity
Components promote a modular approach to building user interfaces. By breaking down the UI into smaller, reusable pieces, components make it easier to manage and maintain code.
ii) Re-usability
Components are designed to be reusable. Once you've created a component, you can use it multiple times throughout your application.
iii) Encapsulation
Components encapsulate their own logic and UI, making it easier to reason about and debug code. Each component operates independently, with clearly defined inputs (props) and outputs (rendered UI).
iv) Composition
React components can be composed together to create complex UIs from simple building blocks. Developers can nest components within one another, combining their functionality to build intricate user interfaces.
v) Separation of Concerns
Components encourage separation of concerns by dividing the UI into smaller, specialized units. Each component is responsible for a specific piece of functionality or user interface element, such as a button, form, or navigation menu.
vi) Performance Optimization
React's virtual DOM and reconciliation algorithm optimize rendering performance by efficiently updating only the parts of the UI that have changed.Component LifeCycle
In React, functional components follow a specific lifecycle, managed primarily through hooks such as
useState
,useEffect
, and others. Here’s an overview of the lifecycle stages and how they are handled in functional components.
i) Initialization
This stage involves setting up initial state and preparing any necessary variables or context.
Setting up state with useState -const [state, setState] = useState(initialState);
ii) Mounting
This is when the component is first added to the DOM.
UsinguseEffect
to run code on mount -useEffect(() => { // Code to run on mount return () => { // Cleanup code to run on unmount }; }, []); // Empty dependency array ensures this runs only on mount and unmount
iii) Updating
This stage occurs whenever the component's state or props change, triggering a re-render.
Reacting to state or prop changes -useEffect(() => { // Code to run on state or prop change }, [dependency1, dependency2]); // Dependencies are the state/props to watch for changes
iv) Unmounting
This is when the component is removed from the DOM.
Cleanup withuseEffect
return function -useEffect(() => { // Mounting code return () => { // Unmounting (cleanup) code }; }, []); // Runs cleanup when component unmounts