Nice and succinct, the dynamic initial value / rerender issue has bitten me a couple of times!
It is worth noting though that there are some issues with the useEffect technique. For example, if you have a parent component passing props to a child (e.g. a form), there is a chance that you can overwrite the child's state on rerender, such as removing a user's input selection.
Another possibility to force a rerender based on outside conditions changing is by using the React key prop - there's a good article by TK Dodo on that method here: tkdodo.eu/blog/putting-props-to-us...
He makes a good point that the useEffect method is possibly an antipattern, although it does apparently fix the issue initially, it could cause hard-to-debug errors down the track.
Worth keeping in mind!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nice and succinct, the dynamic initial value / rerender issue has bitten me a couple of times!
It is worth noting though that there are some issues with the useEffect technique. For example, if you have a parent component passing props to a child (e.g. a form), there is a chance that you can overwrite the child's state on rerender, such as removing a user's input selection.
Another possibility to force a rerender based on outside conditions changing is by using the React key prop - there's a good article by TK Dodo on that method here: tkdodo.eu/blog/putting-props-to-us...
He makes a good point that the useEffect method is possibly an antipattern, although it does apparently fix the issue initially, it could cause hard-to-debug errors down the track.
Worth keeping in mind!