Open AndyOGo opened 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} /> }
https://github.com/jamiebuilds/unstated-next#3-reducing-re-renders-using-reactmemo-and-usecallback
Better: