useRef()
hook to create a ref that holds the stateful value, initializing it with initialState
.useReducer()
hook that creates a new object every time it's updated and return its dispatch.useMemo()
hook to memoize a pair of functions. The first one will return the current value of the state
ref and the second one will update it and force a re-render.const useGetSet = initialState => { const state = React.useRef(initialState); const [, update] = React.useReducer(() => ({})); return React.useMemo( () => [ () => state.current, newState => { state.current = newState; update(); }, ], [] ); };
const Counter = () => { const [getCount, setCount] = useGetSet(0); const onClick = () => { setTimeout(() => { setCount(getCount() + 1); }, 1_000); }; return <button onClick={onClick}>Count: {getCount()}</button>; }; ReactDOM.render(<Counter />, document.getElementById('root'));
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️