useState and changes in the props
When you call useState
it returns an array with two values in it:
- The current value of that bit of the state
- A function to update the state
If there is no current value when it sets the state to the default value and returns that.
(The default value is the argument you pass to useState
).
If you change the values of props
in your example, then the component rerenders.
useState
returns the current value of that bit of the state. The state has a value, so it doesn't do anything with the argument you pass to useState
. It doesn't matter that that value has changed.
Since nothing else has changed in the output, the rerendered component doesn't update the DOM.
OFC the component "rerenders" when the props change, the useEffect
hook in SingleNumber
is showing you that the "render phase" is run each time the props change.... effects are run each time the component is rendered.
const SingleNumber = (props) => {
const [num] = useState(props.num);
useEffect(() => {
console.log("useEffect called"); // <-- logged each time the component renders
});
return <h3>The number is {num}</h3>;
};
If you added a dependency on props.num
and updated the local state (don't actually do this, it's an anti-pattern in react!), you'll see the UI again update each time the props update.
To answer your queston:
Is it correct to say that a function component with a
useState
renders once and then only changed if the state changed but not if theprops
changed?
No, this is not technically correct to say if "render" to you means strictly react rendered the component to compute a diff, react components rerender when state or props update. Yes, if "render" more generally means you visually see the UI update.