Skip to content

Instantly share code, notes, and snippets.

@torian257x
Created June 26, 2020 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torian257x/70964f80cff4bb2f717fe8f22a7bd7f6 to your computer and use it in GitHub Desktop.
Save torian257x/70964f80cff4bb2f717fe8f22a7bd7f6 to your computer and use it in GitHub Desktop.
const useStateWithRef = (initialState) => {
const [state, _setState] = React.useState(initialState);
const ref = React.useRef(state);
const setState = React.useCallback(
(newState) => {
if (typeof newState === 'function') {
_setState(prevState => {
const computedState = newState(prevState);
ref.current = computedState;
return computedState;
});
} else {
ref.current = newState;
_setState(newState);
}
},
[]
);
return [state, setState, ref];
}
@torian257x
Copy link
Author

typescript


export const useStateWithRef = <T, >(initialState: T): [T, (arg1: T) => void, RefObject<T>] => {
    const [state, _setState] = React.useState(initialState);
    const ref = React.useRef(state);
    const setState = React.useCallback(
        (newState) => {
            if (typeof newState === 'function') {
                _setState((prevState: any) => {
                    const computedState = newState(prevState);
                    ref.current = computedState;
                    return computedState;
                });
            } else {
                ref.current = newState;
                _setState(newState);
            }
        },
        []
    );
    return [state, setState, ref];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment