I want to have a state B that its value is dependent to sate A and when state A value updated, state B value updates subsequently.
The problem is as @Atin Singh stated here changing multiple states in react js useState() hook
const [x, setX] = useState(0)
const [y, setY] = useState(x) // this is just to initialize an initial value to your state y so it will be once set to the value of x and then it doesn't depends on x//
State B value initialized to state A value and doesn't depends on value of state A.
But is there any way to make state B value dependent on state A value?
Here is the simplified code:
export default function App() {
const [a, setA] = useState("");
const [b, setB] = useState(a);
const updateA = () => {
setA("Hi");
};
useEffect(() => {
console.log("a: ", a);
console.log("b: ", b);
});
return (
<div className="App">
<button onClick={updateA}>Update State A</button>
</div>
);
}
you can edit the code from here: https://codesandbox.io/s/nifty-sun-ml843?fontsize=14&hidenavigation=1&theme=dark