React.js

ReactJS Components | Type, Nesting, and Lifecycle for beginners

Published

on

Table of Contents

What is React Component?

A React Component is like a building block for making things in a React app. You can think of it as a small part of what users see and interact with on the screen. Each component does its own job and can be reused in different places. It’s like having Lego pieces that you can use over and over again to build different things.

Important aspects of components

Reusability: Components can be reused in different parts of your application, making it easier to manage and maintain your code.

Encapsulation: Each component is like a little bubble that contains its own logic and styling, keeping things organized and preventing conflicts with other parts of the application.

Composition: Components can be combined or nested within each other to create more complex user interfaces, allowing you to build up your app from smaller, modular pieces.

Lifecycle: Components have a lifecycle with various stages like creation, updating, and destruction. This allows you to hook into different points in a component’s life and perform actions or updates as needed.

State and Props: Components can have their own internal state (data) and receive external data through props (properties). This allows components to be dynamic and interactive, responding to user input or changes in data.

Performance Optimization: Components can be optimized for performance by using techniques like memoization, shouldComponentUpdate, or PureComponent to minimize unnecessary renders and improve the overall speed of your application.

The types of React components

There are two types of React components, Functional Components and Class Components.

Functional Components

These are simple functions that return JSX, which is essentially the UI elements.
They don’t have their own internal state.
They receive data as props and return what should be rendered.
They are easier to read and write.

Example:

// Functional Component
function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
}

// Usage
ReactDOM.render(
    <Welcome name="CodeSick" />,
    document.getElementById('root')
);

Class Components

These are JavaScript classes that extend React.Component.
They have their own state, which allows them to manage data and respond to user input.
They have lifecycle methods like ‘componentDidMount’, ‘componentDidUpdate’, etc., which allow for more control over how the component behaves.

Example:

// Class Component
class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}</h1>;
    }
}

// Usage
ReactDOM.render(
    <Welcome name="CodeSick" />,
    document.getElementById('root')
);

Both types of components accomplish the same task of rendering UI elements, but they differ in how they are defined and how they manage data and behavior. Functional components are simpler and usually sufficient for basic UI rendering, while class components offer more features and control for complex UIs with state management and lifecycle events.

What is the Nesting Components in ReactJS

Nesting components in React is like putting one thing inside another. Imagine building a house: you have bricks, windows, and doors. You put the bricks together to make walls, and then you put the windows and doors into the walls to build the house.

Similarly, in React, you can have smaller components, like buttons or text inputs, and you can put them inside bigger components, like a header or a sidebar. This helps you organize your code and build more complex things by combining simpler parts.

// Logo component
function Logo() {
    return <img src="logo.png" alt="Logo" />;
}

// Navigation component
function Navigation() {
    return (
        <nav>
            <ul>
                <li><a href="/">Home</a></li>
                <li><a href="/about">About</a></li>
                <li><a href="/contact">Contact</a></li>
            </ul>
        </nav>
    );
}

// Header component
function Header() {
    return (
        <header>
            <Logo />
            <Navigation />
        </header>
    );
}

// Usage
ReactDOM.render(
    <Header />,
    document.getElementById('root')
);

In this example, the ‘Header’ component nests the ‘Logo’ and ‘Navigation’ components within it. When ‘Header’ is rendered, it will also render the ‘Logo’ and ‘Navigation’ components inside it.

Nesting components helps in creating a modular and maintainable codebase, as each component can focus on a specific part of the UI. It also promotes reusability, as components can be reused in different parts of the application.

Components Lifecycle in ReactJS

In React, think of a component’s lifecycle like the different stages of a plant’s growth. Here’s a simplified explanation,

Planting (Mounting)

  • Planting Seeds (constructor): This is where you prepare things, like setting up a garden bed. You do initial setup, like setting initial state or binding functions.
  • Growing (render): This is where your plant starts to grow and take shape. You create the visual parts of your component here.
  • Blooming (componentDidMount): Once your plant is fully grown, it blooms. This is where you do extra stuff, like watering it or adding decorations. Similarly, in React, you might fetch data or set up timers here.

Growing Further (Updating)

  • Checking for Growth ( shouldComponentUpdate() ): Before your plant grows more, you might check if it needs to grow. Similarly, in React, you might check if your component needs to update based on new information.
  • Growing More ( render() ): If your plant needs to grow more, it does so here. Similarly, in React, you update the visual parts of your component.
  • Adjusting to Changes ( componentDidUpdate() ): After your plant grows more, you might adjust it based on its new size. Similarly, in React, you might do extra stuff after an update, like updating the state or interacting with the DOM.

End of Life (Unmounting)

  • Harvesting (componentWillUnmount): When your plant is done growing and you want to remove it, you harvest it. Similarly, in React, you clean up anything your component might have used, like event listeners or timers, before it’s removed from the screen.

These stages help you manage your components behavior over time, ensuring they grow and change smoothly without causing issues.

Trending

Exit mobile version