jamiebuilds / unstated-next

200 bytes to never think about React state management libraries ever again
MIT License
4.18k stars 145 forks source link

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

Open AndyOGo opened 3 years ago

AndyOGo commented 3 years ago

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} />
}