reactjs - How to use `setState` callback on react hooks - Stack Overflow

PHOTO EMBED

Mon Apr 25 2022 13:34:29 GMT+0000 (Coordinated Universal Time)

Saved by @dah007 #javascript

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]);
content_copyCOPY

https://stackoverflow.com/questions/56247433/how-to-use-setstate-callback-on-react-hooks