Last active
November 25, 2020 16:08
-
-
Save andyrichardson/28062efd7eb1a615089975886668aaa6 to your computer and use it in GitHub Desktop.
A reducer hook which calls the provided reducer function synchronously and returns the updated state from the dispatch.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useCallback, useRef } from 'react'; | |
export const useSynchronousReducer = <S, A>( | |
reducer: (s: S, a: A) => S, | |
initialState: S | |
) => { | |
const stateRef = useRef(initialState); | |
const [state, setState] = useState<S>(stateRef.current); | |
const dispatch = useCallback<(a: A) => S>((action) => { | |
stateRef.current = reducer(stateRef.current, action); | |
setState(stateRef.current); | |
return stateRef.current; | |
}, []); | |
return [state, dispatch] as const; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment