React hooks are now preferred for state management. Calling setState multiple times in one function can lead to unpredicted behavior read more.
Think of setState()
as a request to update the component. Reading state right after calling setState()
a potential pitfall.
useState
React hookReturns 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!");
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();
State right after calling setState will have value before the update.
const [value, setValue] = useState("");setValue("React is awesome!");console.log(value) // ""
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