ARTICLE AD BOX
I am using React with TypeScript and I am trying to keep a local state in sync with a prop value.
The idea is simple, when the prop changes, the local state should update. However, when the user manually updates the local state, it should not be immediately overridden unless the prop actually changes.
Here is a minimal reproducible example.
import { useEffect, useState } from "react" type Props = { initialValue: number } function Counter(props: Props) { const [value, setValue] = useState(props.initialValue) useEffect(function () { setValue(props.initialValue) }, [props.initialValue, value]) return ( <button onClick={function () { setValue(value + 1) }} > {value} </button> ) } export default CounterWith this setup, the component enters an infinite re-render loop.
If I remove value from the dependency array, the loop stops, but then I feel like I am doing something wrong regarding state and prop synchronization.
My questions are:
Why does including value in the dependency array cause an infinite loop.
What is the recommended pattern for syncing props to local state in this scenario.
Is using useEffect for prop to state synchronization the correct approach here.
What I have tried:
Removing value from the dependency array.
Initializing the state only inside useState.
However, I am not confident about what the clean and idiomatic solution is.
