Languages

React - setState with a callback function (useState hook)

0 points
Asked by:
Lily
208

Hi!

I want to display some information after updating the state value in React functional component. Is there a way to call setState() with a callback function that console.log some text?

This is what I want to do:

import React, { useState } from 'react';

const App = () => {
  const [state, setState] = useState(0);

  const handleClick = () => {
    setState(1, () => {
      console.log('state updated succesfully');
    });
  };

  return (
    <div>
      <h1>{state}</h1>
      <button onClick={handleClick}>update</button>
    </div>
  );
};

export default App;
0 answers
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join