HiveBrain v1.2.0
Get Started
← Back to all entries
snippetreactCritical

How to use `setState` callback on react hooks

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
hookscallbacksetstateusereacthow

Problem

React hooks introduces useState for setting component state. But how can I use hooks to replace the callback like below code:

setState(
  { name: "Michael" },
  () => console.log(this.state)
);


I want to do something after the state is updated.

I know I can use useEffect to do the extra things but I have to check the state previous value which requires a bit code. I am looking for a simple solution which can be used with useState hook.

Solution

You need to use useEffect hook to achieve this.
const [counter, setCounter] = useState(0);

const doSomething = () => {
setCounter(123);
}

useEffect(() => {
console.log('Do something after counter has changed', counter);
}, [counter]);


If you want the useEffect callback to be ignored during the first initial render, then modify the code accordingly:
import React, { useEffect, useRef } from 'react';

const [counter, setCounter] = useState(0);
const didMount = useRef(false);

const doSomething = () => {
setCounter(123);
}

useEffect(() => {
// Return early, if this is the first render:
if ( !didMount.current ) {
return didMount.current = true;
}
// Paste code to be executed on subsequent renders:
console.log('Do something after counter has changed', counter);
}, [counter]);

Context

Stack Overflow Q#56247433, score: 432

Revisions (0)

No revisions yet.