Skip to content

Instantly share code, notes, and snippets.

@salvoravida
Created November 28, 2019 22:02
Show Gist options
  • Save salvoravida/b6e24ec7c0e1140365712e25806991c8 to your computer and use it in GitHub Desktop.
Save salvoravida/b6e24ec7c0e1140365712e25806991c8 to your computer and use it in GitHub Desktop.
useStateRef
import { useState, useCallback } from 'react';
export const useStateRef = initialState => {
const [state, setState] = useState(() => ({
current: typeof initialState === 'function' ? initialState() : initialState
}));
const setStateRef = useCallback(
(setter, forceRender) => {
setState(prev => {
const current = typeof setter === 'function' ? setter(prev.current) : setter;
if (forceRender) return { current };
prev.current = current;
return prev;
});
},
[setState]
);
return [state, setStateRef];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment