Skip to content

Instantly share code, notes, and snippets.

@abhishekbhardwaj
Last active February 15, 2021 14:36
Show Gist options
  • Save abhishekbhardwaj/bd6a33bd1663fdb98856d7d014e1ea00 to your computer and use it in GitHub Desktop.
Save abhishekbhardwaj/bd6a33bd1663fdb98856d7d014e1ea00 to your computer and use it in GitHub Desktop.
useStateIfMounted: Use this instead of useState with Inertia.js if running into "Can't perform a React state update on an unmounted component". The error happens because the server-side redirect doesn't give your component enough time to clean up.
import { useEffect, useRef, useState } from "react";
export default function useStateIfMounted<T>(
initialState: T
): [T, (newState: T) => void] {
const isMounted = useRef(true);
const [state, setState] = useState(initialState);
useEffect(() => {
return () => {
isMounted.current = false;
};
}, []);
const setStateIfMounted = (newState: any) => {
if (isMounted.current) {
setState(newState);
}
};
return [state, setStateIfMounted];
}
// Usage
const [name, setName] = useStateIfMounted("");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment