Skip to content

Create a common hook for syncing state and props #19

@abinashpanda

Description

@abinashpanda

Currently, the useSyncedState hook updates the local state with the props. But this hook still lacks functionality to update to call onChange handlers from the props on updating local state. So to solve this problem almost every component has implemented a different logic. This is not maintainable in long term. There should be a common hook in the form of

const [inputValue, setInputValue] = useSyncedState(value, {
  // callback function called when the state is updated
  onStateChange: (updatedValue) => {
    onChange?.(updatedValue)
  },
  // comparator function to compare when the state and prop differs
  // for perfomance optimization the hook should use shallow comparision by default
  // but for the complex cases like date picker, user should have a way to provide a comparator function
  comparator: (a, b) => a === b
})

In the above example, the value and onChange are props provided to the component, when we want to run it as a controlled component. In absence of these props, the component should behave as an uncontrolled component. So it should also maintain its own state. But this poses a challenge of inputValue state with value prop. If there is a new value, it should update the inputValue and if there is any change in inputValue, it should update the value by calling the onChange prop.

This hook also aims to provide a simpler mental model to the component developer to consider this element as a simple uncontrolled element and use inputValue and setInputValue as it is. The logic of syncing should be handled by hook itself.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions