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

useDistinct #92

Open
benneq opened this issue Jan 30, 2019 · 3 comments
Open

useDistinct #92

benneq opened this issue Jan 30, 2019 · 3 comments
Labels
enhancement New feature or request

Comments

@benneq
Copy link
Contributor

benneq commented Jan 30, 2019

I'd like to have some useDistinct hook, which takes a value (or another hook) and only changes state if the returned value has changed.

It's kinda the opposite way of useMemo. It should rerender based on output instead of input value.

I'm not sure if that's possible at all...

Usage:

const compareFn = (oldValue, newValue) => {
    return oldValue[0] === newValue[0];
}

const MyComponent = (props) => {
    const [state, setState] = useDistinct(useState("foo"), compareFn);
  
    console.log("rerendered", state)

    return (
      <button onClick={() => setState("foo")}>Change State</button>
    )
}

Explanation:
When not using useDistinct, every call to setState will rerender the component. Even if you call setState(state).
When using useDistinct, it should check for === equality. Or you can provide a custom comparison function which does the equality check.

@streamich
Copy link
Owner

If your function is pure it should be the same as memoizing input arguments.

@benneq
Copy link
Contributor Author

benneq commented Jan 30, 2019

Of course the purpose are non-pure functions as well 😄

Something like useRouter, which takes no input arguments, but produces values when for example the user changes the URL.

I tried to play around with useCallback and useMemo, but I couldn't figure out a solution. It always rerenders.

@wardoost wardoost added the enhancement New feature or request label Mar 31, 2019
@wardoost wardoost changed the title useDistinct possible? useDistinct Mar 31, 2019
@dpikt
Copy link

dpikt commented May 16, 2019

@benneq I'm unable to reproduce the use case you provided- it only logs "rendered" once, even after I pressed the button. For reference, I'm using react 16.8.6.

@dpikt dpikt mentioned this issue May 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants