Sobes.tech
Middle+

How to update the state of a component?

sobes.tech AI

Answer from AI

In React, to update the component's state, the useState hook (in functional components) or the setState method (in class components) is used.

Example with a functional component:

import React, { useState } from 'react';

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

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

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

When calling setCount, React schedules an update of the component with the new state value, which leads to a re-render with updated data.

It is important to update the state using update functions if the new value depends on the previous one, to avoid issues with asynchronous updates.