Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useState and callback function

In the class component, the setState() method can take a callback function, but in a functional component when I give a callback to costume setState this warning occurs: Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect(). I need my state set, and then the page will redirect. But I don't have any idea.

like image 471
S. Hesam Avatar asked Nov 27 '19 07:11

S. Hesam


1 Answers

Instead of passing a callback function, use useEffect hook, and do something like this to achieve the desired result.

 useEffect(() => {
    console.log('state changed', your-state-variable)
    // write your callback function here
  }, [your-state-variable]);
like image 73
coderLogs Avatar answered Oct 28 '22 09:10

coderLogs