Tag: Class Components

  • Functional vs. Class Components in React

    React components are the building blocks of any React application. There are two main types: Functional Components and Class Components. Understanding the differences between them is key to writing modern, efficient React applications.


    What are Functional Components?

    Functional components are JavaScript functions that return JSX. They are simpler, easier to read, and preferred in modern React development.

    ✅ Key Features:

    • Simpler syntax – Just a function returning JSX.
    • Hooks support – Can use useState, useEffect, etc.
    • Better performance – No overhead from class instantiation.

    Example of a Functional Component

    import { useState } from "react";
    
    function Counter() {
      const [count, setCount] = useState(0);
      return (
        <div>
          <p>{count}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }

    What are Class Components?

    Class components are ES6 classes that extend React.Component. Before hooks were introduced, they were the primary way to manage state and lifecycle methods.

    ⚠️ Key Features:

    • Uses this.state and this.setState for state management.
    • Lifecycle methods like componentDidMount and componentDidUpdate.
    • More boilerplate compared to functional components.

    Example of a Class Component

    import React, { Component } from "react";
    
    class Counter extends Component {
      constructor(props) {
        super(props);
        this.state = { count: 0 };
      }
    
      increment = () => {
        this.setState({ count: this.state.count + 1 });
      };
    
      render() {
        return (
          <div>
            <p>{this.state.count}</p>
            <button onClick={this.increment}>Increment</button>
          </div>
        );
      }
    }

    Functional vs. Class Components: Key Differences

    FeatureFunctional ComponentsClass Components
    SyntaxSimple functionES6 class
    State ManagementuseState Hookthis.state & setState
    Lifecycle MethodsuseEffect HookcomponentDidMount, etc.
    PerformanceMore efficientSlightly slower due to class overhead
    Code ComplexityLess boilerplateMore setup required

    Why Functional Components Are Preferred

    Modern React development favors functional components because they:

    Require less code

    Improve performance

    Support hooks for better state management

    Are easier to read and test

    With the introduction of React Hooks (React 16.8), almost everything class components could do is now possible in functional components—making class components largely obsolete for new projects.


    Summary

    • Functional components are the modern, recommended way to write React components.
    • Class components were used before hooks but are now less common.
    • Hooks like useState and useEffect make functional components powerful and easy to use.

    References

    1. React Official Docs – Components
    2. Understanding React Functional Components
    3. Class Components vs. Functional Components

  • Components & State Management in React

    In React, components are the building blocks of the UI, and state management is how data is stored and updated within them. Understanding how components work and how to manage state effectively is essential for building scalable React applications.


    What Are Components?

    A component is a reusable piece of UI that can be independent or composed with other components.

    Types of Components:

    1. Functional Components (Recommended)
    2. Class Components (Legacy)

    ✅ Functional Component (Modern Approach)

    function Greeting({ name }) {
      return <h1>Hello, {name}!</h1>;
    }

    ❌ Class Component (Older Approach)

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

    React now favors functional components with hooks because they are simpler and more efficient.


    State Management in React

    State is data that changes over time within a component. React re-renders the UI whenever state updates.

    Using useState Hook

    The useState hook allows functional components to store and update state.

    ✅ Example of useState

    import { useState } from "react";
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }

    How useState Works:

    • useState(0): Initializes state with 0.
    • setCount(count + 1): Updates state, triggering a re-render.

    Props vs. State

    FeaturePropsState
    DefinitionData passed from parent to childData managed within a component
    MutabilityRead-only (cannot be modified by child)Can be updated with setState (or useState)
    Example<Greeting name="Alice" />const [count, setCount] = useState(0);

    Lifting State Up

    When multiple components need shared state, state is lifted up to the nearest common ancestor.

    ✅ Example of Lifting State

    function ParentComponent() {
      const [value, setValue] = useState("Hello");
      return <ChildComponent value={value} setValue={setValue} />;
    }
    
    function ChildComponent({ value, setValue }) {
      return (
        <div>
          <p>{value}</p>
          <button onClick={() => setValue("Updated!")}>Update</button>
        </div>
      );
    }

    Advanced State Management

    For larger applications, React Context or state management libraries like Redux or Zustand are used.

    Using Context API (Avoid Prop Drilling)

    const ThemeContext = React.createContext("light");
    
    function App() {
      return (
        <ThemeContext.Provider value="dark">
          <ChildComponent />
        </ThemeContext.Provider>
      );
    }
    
    function ChildComponent() {
      const theme = React.useContext(ThemeContext);
      return <p>Current theme: {theme}</p>;
    }

    Summary

    • Components are the fundamental building blocks of React.
    • State is mutable data that causes re-renders when updated.
    • Props pass data between components, but cannot be modified.
    • Lifting state up allows shared state between components.
    • Context API helps manage global state without prop drilling.

    References

    1. React Docs – Components
    2. React Docs – State and Lifecycle
    3. React Docs – Context