Can't perform a React state update on an unmounted component
2021-03-09
>Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
import { useCallback, useState } from 'react';
// Returning a new object reference guarantees that a before-and-after
// equivalence check will always be false, resulting in a re-render, even
// when multiple calls to forceUpdate are batched.
export default function useForceUpdate(): () => void {
const [ , dispatch ] = useState<{}>(Object.create(null));
// Turn dispatch(required_parameter) into dispatch().
const memoizedDispatch = useCallback(
(): void => {
dispatch(Object.create(null));
},
[ dispatch ],
);
return memoizedDispatch;
}
>React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
>useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.