In this article, we will see how to use the setState() callback with React hooks.

The setState() method is used to update the state of a component. When we call the setState(), React updates the component’s state and re-renders the component. However, sometimes we may need to perform additional actions after the state has been updated. This is where we use the setState() callback.

Following is the example of using the setState callback with react functional component

import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    console.log(`Count is now ${count}`);
  }, [count]);

  function handleClick() {
    setCount(count + 1, () => {
      console.log(`Count has been incremented to ${count + 1}`);
    });
  }

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

export default Counter;

Explanation:

In the above example, we have defined a functional component called Counter that uses the useState() hook to manage the state of a counter and useEffect() hook that logs the current value of the count to the console every time the count changes.

When the user clicks the “Increment” button, we update the count state using the setCount() method. We pass in a callback function that logs the new count value to the console.

By using the setCount() callback, we perform additional actions based on the updated state. In this case, we are logging the new count value to the console.

Categorized in:

Tagged in: