How to make sure a React state using useState() hook has been updated?

I encountered something like this recently (SO question here), and it seems like what you’ve come up with is a decent approach.

You can add an arg to useEffect() that should do what you want:

e.g.

useEffect(() => { ... }, [submitted])

to watch for changes in submitted.

Another approach could be to modify hooks to use a callback, something like:

import React, { useState, useCallback } from 'react';

const useStateful = initial => {
  const [value, setValue] = useState(initial);
  return {
    value,
    setValue
  };
};

const useSetState = initialValue => {
  const { value, setValue } = useStateful(initialValue);
  return {
    setState: useCallback(v => {
      return setValue(oldValue => ({
        ...oldValue,
        ...(typeof v === 'function' ? v(oldValue) : v)
      }));
    }, []),
    state: value
  };
};

In this way you can emulate the behavior of the ‘classic’ setState().

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)