I have two components, one placed inside the other. The children component prints the state passed by the parent and updates the state once with useEffect. In the parent component I'm using setState (an object with boolean values) and passing the state to all the children.
Parent component:
export default function App() {
const [state, setState] = useState({
one: false,
two: false,
three: false
});
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<ChildComponent
value={state.one}
setState={(val) => setState({ ...state, one: val })}
/>
<ChildComponent
value={state.two}
setState={(val) => setState({ ...state, two: val })}
/>
<ChildComponent
value={state.three}
setState={(val) => setState({ ...state, three: val })}
/>
</div>
);
}
Child Component:
import { useEffect } from "react";
export default function ChildComponent({ value, setState }) {
useEffect(() => {
console.log("updated");
setState(!value);
}, []);
return (
<>
<p>{value ? "true" : "false"}</p>
</>
);
}
Both components are really simple, and I'm expecting to see all boolean values being true (because the child components are modifying the state). The problem is that only the last item on the state is being updated. Can someone explain what is wrong with my code? A working example