17 Feb 2024




Beginner

In React.js, the useState hook is used to add state variables to functional components.

Syntax of the useState hook is as follows:

const [stateVariable, setStateFunction] = useState(initialState);
  • stateVariable: This is the current state value. You can read the current state from this variable.
  • setStateFunction: This is a function used to update the state. When called, it replaces the current state value with the new value provided as an argument.
  • initialState: This is the initial state value that you want to assign to the state variable when the component is first rendered.

Here's a breakdown of how to use useState:

import React, { useState } from 'react';

function ExampleComponent() {
  // Declare a state variable named "count" and its corresponding setState function
  const [count, setCount] = useState(0);

  // Here, "count" is the state variable holding the current value of the count
  // "setCount" is a function to update the value of "count"

  return (
    <div>
      <p>You clicked {count} times</p>
      {/* Button that updates the state when clicked */}
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default ExampleComponent;

In this example, count is the state variable, setCount is the function to update the state, and 0 is the initial value of the state variable.

Key points of useState hook:

  • State Initialization:

    • useState allows you to declare state variables and initialize them with an initial value.
    • Example:
      const [state, setState] = useState(initialValue);
      
  • Array Destructuring:

    • The useState Hook returns an array where the first element is the current state value, and the second element is a function to update the state.
    • Example:
      const [state, setState] = useState(initialValue);
      
  • Functional Updates:

    • setState function can accept a function as an argument, which receives the previous state and returns the new state.
    • This is useful when the new state depends on the previous state.
    • Example:
      setState(prevState => prevState + 1);
      
  • Lazy Initialization:

    • The initial state argument is only used during the initial render, similar to how state works in class components.
    • Example:
      const [count, setCount] = useState(() => expensiveInitialState());
      
  • Multiple State Variables:

    • You can use useState Hook multiple times in a single component to manage multiple state variables independently.
    • Example:
      const [name, setName] = useState('John');
      const [age, setAge] = useState(25);
      
  • Immutable Updates:

    • State updates with useState are immutable, always use the setState function provided by the Hook to update state.
    • Example:
      setAge(prevAge => prevAge + 1);
      
  • Functional Component State Management:

    • useState allows functional components to have local component state, making them more powerful and flexible.
    • Example:
      function Counter() {
        const [count, setCount] = useState(0);
      
        return (
          <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
          </div>
        );
      }
      
  • Rendering Trigger:

    • When the state is updated using setState, React re-renders the component and any child components that rely on that state.
    • Example:
      const handleChange = (e) => {
        setValue(e.target.value);
      };
      
  • Performance Optimization:

    • React batches state updates to improve performance. Multiple setState calls in the same synchronous execution context are batched together.
    • Example:
      const handleIncrement = () => {
        setCount(count + 1);
        setCount(count + 1); // React batches these updates
      };
      
  • Asynchronous Updates:

    • useState updates are asynchronous, React may batch multiple setState calls and apply them in a single update for performance reasons.
    • Example:
      useEffect(() => {
        console.log("Count updated: ", count);
      }, [count]);
      
  • Functional Paradigm:

    • useState promotes the functional paradigm by allowing components to manage state without the need for classes and lifecycle methods.
    • Example:
      function ExampleComponent() {
        const [count, setCount] = useState(0);
        
        const handleIncrement = () => {
          setCount(count + 1);
          console.log("Count after increment: ", count); 
        };
      }
      
reactjs
usestate
hook