Skip to content

Instantly share code, notes, and snippets.

@memon07
Created June 15, 2020 14:56
Show Gist options
  • Save memon07/bc9b07054777aaa3c80d84a007036a51 to your computer and use it in GitHub Desktop.
Save memon07/bc9b07054777aaa3c80d84a007036a51 to your computer and use it in GitHub Desktop.
Custom hook to prevent memory leakage
import React, {
Dispatch,
SetStateAction,
useState,
useRef,
useEffect,
} from 'react';
export default function useMountedState<S>(
initialState: S | (() => S),
): [S, Dispatch<SetStateAction<S>>] {
const [state, setState] = useState(initialState);
const ref = useRef(false);
const updateState = (value: SetStateAction<S>) => {
ref.current && setState(value);
};
useEffect(() => {
ref.current = true;
return () => {
ref.current = false;
};
}, []);
return [state, updateState];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment