0

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)}
    />
}
AJP
  • 26,547
  • 23
  • 88
  • 127
  • It looks totally fine, this is the recommended way, see: [How to sync props to state using React hooks : setState()](https://stackoverflow.com/questions/54625831/how-to-sync-props-to-state-using-react-hooks-setstate) – Emile Bergeron Jun 17 '21 at 14:38
  • Thanks! The comments section under the accepted answer is pretty mixed which makes sense for the question as it's not manipulating the state itself and could (should) just use the props directly. – AJP Jun 18 '21 at 12:29

0 Answers0