Update React Hooks State During Render Using useMemo

This seems to be an elegant way to reduce boiler plate to me. I created a codesandbox to validate its behaviour.

const UnitUnderTest = ({prop}) => {
  let [someState, setSomeState] = useState(false);

  const lessCodeThanCheckingPrevRow = useMemo(
    () => setSomeState(current => !current), 
    [prop],
  );

  useEffect(() => console.log('update finished'), [prop])

  console.log('run component');

  return `State: ${someState}`;
}

const App = () => {
  const [prop, setProp] = useState(false);
  const handleClick = () => setProp(current => !current);

  return (
    <div>
      <button onClick={handleClick} >change prop</button>
      <UnitUnderTest prop={prop} />
    </div>
  )
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit recursing-hopper-4ynjm

Output when clicking the button to change the prop passed to the component:

> run component 
> run component 
> update finished 

As you can see the component has been run twice before the update cycle completed. This is equivalent to the the behaviour of getDerivedStateFromProps.

I guess that there is no deeper thought behind why the docs propose a slightly different technique. In a way this is a manual check too but in a neat way. +1 for the idea.


Use the useEffect hook for this behavior. useMemo is used to store a value that might not necessarily change over each renders, so that you avoid useless re-calculation of that value