In this example, I have shared how to useState hook setter incorrectly overwrites state? A solution to ensure the setState from changeValue1 and changeValue2 gets the latest state is by using a callback (having the fresh current state as a parameter):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import React, { useState } from "react"; const Test = () => { const [state, setState] = useState({ value1: "1", value2: "2" }); const changeValue1 = () => { setState((state) => ({ ...state, value1: "new 1" })); }; const changeValue2 = () => { setState((state) => ({ ...state, value2: "new 2" })); }; // ... }; |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.