React setState does not immediately update the state

Application Development 27-Dec-2023

React hooks are now preferred for state management. Calling setState multiple times in one function can lead to unpredicted behavior read more.

React State

Think of setState() as a request to update the component. Reading state right after calling setState() a potential pitfall.

useState React hook

Returns a stateful value, and a function to update it. The function to update the state can be called with a new value or with an updater function argument.

const [value, setValue] = useState("");setValue("React is awesome!");

updater argument

If you need to set the state based on the previous state. Updater argument is guaranteed to fire after the update has been applied.

The first argument is an updater function with the signature:

(state) => newState

Use of updater function for toggle

const [isVisible, setVisible] = useState(false);const toggleVisible = setVisible((state) => !state);toggleVisible();

How we can setState and get state right after calling setState?

State right after calling setState will have value before the update.

const [value, setValue] = useState("");setValue("React is awesome!");console.log(value) // ""

We have some options.

Calling updater just to get the latest value.

const [value, setValue] = useState("");setValue("React is awesome!");setValue((state) => {
console.log(state); // "React is awesome!"

return state;

Custom hook for setState with async state selector.

const [value, setValue, getValue] = useSetState("");setValue("React is awesome!");console.log(await getValue()); // "React is awesome!"

Source: Medium