I have a few form components that for performance reasons, only dispatch changes to their values (to their parent component) when they blur. The naive implementation is as follows:
function TextField (props)
{
const [value, set_value] = useState(props.value)
return <input
type="text"
value={value}
onChange={e => set_value(e.currentTarget.value)}
onBlur={() => props.on_blur(value)}
/>
}
This is ok until another form component alters the value represented by this component. For example, setting a value on another field when this field is empty causes the other component to also set a default value of this field based on the other field. In this case however this form component does not update as it has the original props.value in its useState.
I would like there to be a way to tell the useState to update its value when it is changed from its parent.
Currently I am using the following pattern but I curious if there is a better / more elegant way of doing this:
function TextField (props)
{
const [value, set_value] = useState(props.value)
useEffect(() => set_value(props.value), [props.value]) // <---
return <input
type="text"
value={value}
onChange={e => set_value(e.currentTarget.value)}
onBlur={() => props.on_blur(value)}
/>
}