Sobes.tech
Junior

What is the use of the useState directive?

sobes.tech AI

Answer from AI

useState is a React hook that allows adding state to functional components. It returns an array with two elements: the current state value and a function to update it. When the update function is called, the component re-renders with the new value.

Example of usage:

import { useState } from 'react';

function Counter() {
  // 'count' is the current state, 'setCount' is the function to update it
  const [count, setCount] = useState(0);

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

Main features:

  • Adds state: Allows using state in components, previously only available in class components.
  • Update function: Returns a special function to change the state.
  • Re-render: Changing state via the update function causes the component to re-render.
  • Primitives and objects: Can store any data types: numbers, strings, booleans, objects, arrays.
  • Lazy initialization: The initial value can be a function that executes only during the first render, useful for expensive calculations.
const [data, setData] = useState(() => {
  // Expensive calculations are performed only once
  const initialData = someExpensiveCalculation();
  return initialData;
});