Hack Frontend Community

How useState Works in React?

useState is a hook in React that allows adding state to functional components. Before hooks appeared, state was only available in class components. With useState, state can be used in functional components, simplifying code writing and maintenance.

How Does useState Work?

  • State initialization. The useState hook accepts initial value and returns array with two elements:

    1. Current state value.
    2. Function to update state.
  • State update. When state changes, component re-renders with new state value.

useState Usage Example

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0); // Initialize state with initial value 0

  const increment = () => {
    setCount(count + 1); // Update state
  };

  return (
    <div>
      <p>Counter: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

Important Points When Using useState

  • State update function can be called with new state value or function that accepts previous state:
  setCount(prevCount => prevCount + 1);
  • If you want to update state based on its previous value, use function passed to setCount to avoid problems with update asynchrony.

Update Function Example

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(prevCount => prevCount + 1); // Use previous state
  };

  return (
    <div>
      <p>Counter: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

useState and re-rendering:

When state changes, React re-renders component with new state value, allowing creation of dynamic and interactive interfaces.

How Does useState(() => compute()) Work?

When you pass function to useState, this function will be executed only once — on component's first render. This can be useful for performance optimization if calculations are heavy or if you need to do something before setting initial state.

Instead of calculating value every time during render, React will call this function only once and use result as initial state.

Usage Example:

import { useState } from "react";

// Function for complex calculations
function compute() {
  console.log("Calculations executing...");
  return 42; // For example, complex logic calculation
}

function MyComponent() {
  const [count, setCount] = useState(() => compute()); // compute called only once

  return (
    <div>
      <p>Value: {count}</p>
    </div>
  );
}