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

usePureState #60

Open
cloudever opened this issue Nov 1, 2018 · 7 comments
Open

usePureState #60

cloudever opened this issue Nov 1, 2018 · 7 comments
Labels
enhancement New feature or request

Comments

@cloudever
Copy link
Contributor

Use the same as useState but with shallow compare

@streamich
Copy link
Owner

Do you mean it would not re-render if props didn't change?

@revskill10
Copy link
Contributor

Could react-fast-compare help here ?

@streamich
Copy link
Owner

react-fast-compare does deep compare, as I understand, not shallow.

@cloudever
Copy link
Contributor Author

I mean that if use useState with object like this.setState, it would be great to skip update using shallow compare of object values like that

function Component() {
  const [state, setState] = usePureState({ a: 1, b: 2 })

  // skip update
  setState({ a: 1 }) // merges automatically
  // updates
  setState({ a: 2})
 
}

@streamich
Copy link
Owner

Yeah, sounds like something useful. I guess, could be easy to do, too, just with just a single loop that shallow-checks all values.

@chriswilty
Copy link

This is how React do shallowEquals:
https://github.com/facebook/react/blob/master/packages/shared/shallowEqual.js

I would hope that usePureState could get included as a built-in hook. Saves us all re-implementing (read copy-pasting) the above comparator.

@wardoost wardoost added the enhancement New feature or request label Mar 31, 2019
@dpikt
Copy link

dpikt commented May 16, 2019

Could this be implemented via a hook that allows a custom comparator function to be used for state updates? It looks like useState already avoids re-renders for shallowly equal updates, we would just need to expand the concept of what an "equal" update is.

// using default useState comparator 
const [ state, setState ] = useDistinctState('a')
setState('A') // will update
...
// using a custom comparator
const [ state, setState ] = useDistinctState('a', 
    (prev, next) => prev.toUpperCase() === next.toUpperCase()
)
setState('A') // won't update
...
// solving issue use case
function usePureState (initialValue) {
   return useDistinctState(initialValue, shallowEqual)
}

(I just came from reading #92 so that's part of my consideration here.)

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

6 participants