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

Reducing re-renders useCallback optimization should use functional updates #94

Open
AndyOGo opened this issue Jan 12, 2021 · 0 comments

Comments

@AndyOGo
Copy link

AndyOGo commented Jan 12, 2021

If the new state is computed using the previous state, you can pass a function to setState.
https://reactjs.org/docs/hooks-reference.html#functional-updates

https://github.com/jamiebuilds/unstated-next#3-reducing-re-renders-using-reactmemo-and-usecallback

Better:

function useCounter() {
  let [count, setCount] = useState(0)
  let decrement = useCallback(() => setCount((prevCount) => prevCount - 1), [])
  let increment = useCallback(() => setCount((prevCount) => prevCount + 1), [])
  return { count, decrement, increment }
}

let Counter = createContainer(useCounter)

let CounterDisplayInner = React.memo(props => {
  return (
    <div>
      <button onClick={props.decrement}>-</button>
      <p>You clicked {props.count} times</p>
      <button onClick={props.increment}>+</button>
    </div>
  )
})

function CounterDisplay(props) {
  let counter = Counter.useContainer()
  return <CounterDisplayInner {...counter} />
}
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