Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create a common hook for syncing state and props #19

Open
abinashpanda opened this issue Oct 22, 2020 · 0 comments
Open

Create a common hook for syncing state and props #19

abinashpanda opened this issue Oct 22, 2020 · 0 comments

Comments

@abinashpanda
Copy link
Collaborator

abinashpanda commented Oct 22, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant