Here is the CodeSandBox link: https://codesandbox.io/s/stale-prop-one-g92sv?file=/src/App.js
I find the child components will not show the correct counter values after two button clicks, though the counter is actually incrementing:
import "./styles.css";
import { useState } from "react";
const MyComponent = ({ value }) => {
const [counter] = useState(value);
return <span>{counter}</span>;
};
export default function App() {
const [counter, setCounter] = useState(0);
const isVisible = counter !== 1;
console.log(counter);
return (
<div className="App">
<div>
<button onClick={() => setCounter((counter) => counter 1)}>
Click me
</button>
</div>
{isVisible && (
<div>
Message 1 is: <MyComponent value={counter} />
</div>
)}
<div style={isVisible ? { display: "block" } : { display: "none" }}>
Message 2 is: <MyComponent value={counter} />
</div>
</div>
);
}
I try to force child component re-render by assigning counter to its key:
export default function App() {
const [counter, setCounter] = useState(0);
const isVisible = counter !== 1;
console.log(counter);
return (
<div className="App">
<div>
<button onClick={() => setCounter((counter) => counter 1)}>
Click me
</button>
</div>
{isVisible && (
<div>
Message 1 is: <MyComponent key = {counter} value={counter} />
</div>
)}
<div style={isVisible ? { display: "block" } : { display: "none" }}>
Message 2 is: <MyComponent key = {counter} value={counter} />
</div>
</div>
);
}
It works, but I still have no idea why the previous one does not work, since the props.value
in MyComponent
has changed...
Thanks in advance.
CodePudding user response:
With this:
const MyComponent = ({ value }) => {
const [counter] = useState(value);
return <span>{counter}</span>;
};
You're telling React to set the initial state to the first value
prop passed to the component, on mount.
When the component re-renders, the component has already been mounted, so the value passed to useState
is ignored - instead, the counter
in that child is taken from the state of MyComponent
- which is equal to the initial state in MyComponent
, the initial value
prop passed.
For what you're trying to do, you only have a single value throughout the app here that you want to use everywhere, so you should only have one useState
call, in the parent - and then render the counter in the child from the prop, which will change with the parent state.
const MyComponent = ({ value }) => {
return <span>{value}</span>;
};