Skip to content

Instantly share code, notes, and snippets.

@andyrichardson
Last active November 25, 2020 16:08
Show Gist options
  • Save andyrichardson/28062efd7eb1a615089975886668aaa6 to your computer and use it in GitHub Desktop.
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.
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