I keep getting this error for my useEffect.
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
How can I stop getting this warning for my function below?
export default function GetDemo() { const ListLoading = LoadingComponent(Demo); const [appState, setAppState] = useState({ loading: true, posts: null, }); useEffect(() => { axiosInstance.get('demo/all/').then((res) => { const allPosts = res.data; setAppState({ loading: false, posts: allPosts }); }); }, []); return ( <ListLoading isLoading={appState.loading} buckets={appState.posts} /> ); };
I’m not sure what to add in the useEffect dependency array, I’ve tried using setAppState
and the state itself but still getting this warning.
Advertisement
Answer
Check if the component is still mounted before calling setAppState
:
useEffect(() => { let mounted = true; axiosInstance.get('demo/all/').then((res) => { const allPosts = res.data; if (mounted) { setAppState({ loading: false, posts: allPosts }); } }); return () => { mounted = false; }; }, []);