Last active
February 15, 2021 14:36
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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