setState callback hooks code example
Example 1: react callback set staet
setState( { name: "Michael" }, () => console.log(this.state));
Example 2: How to use `setState` callback on react hooks
const [counter, setCounter] = useState(0);
const doSomething = () => {
setCounter(123);
}
useEffect(() => {
console.log('Do something after counter has changed', counter);
}, [counter]);
Example 3: usestate hook callback
const [counter, setCounter] = useState(0);
const doSomething = () => {
setCounter(123);
}
useEffect(() => {
console.log('Do something after counter has changed', counter);
}, [counter]);
Example 4: react functional components setstate callback
const [state, setState] = useState({ name: "Michael" })
const isFirstRender = useRef(true)
useEffect(() => {
if (!isFirstRender.current) {
console.log(state)
}
}, [state])
useEffect(() => {
isFirstRender.current = false
}, [])