Answer the question
In order to leave comments, you need to log in
How to unmount what is not in useEffect?
I have an observer in my component to load content. It turns out when the observer is triggered, there is a request to the server (asynchronous garbage). If I switch from one route to another and switch back, I get the error "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". I found out that this error is caused by a state change in the rest response and so I think that I need to unmount it, but I can only unmount what is in useEffect, and my setstates are not in it)
Question.
How to unmount it?
Answer the question
In order to leave comments, you need to log in
The problem is that you are launching asynchronous actions in useEffect. This is not very correct, it is better to take out the logic separately, and add its results to the stack.
If you need to fix it very quickly without refactoring, then you can add an unmount check so as not to change the state of the unmounted component.
const useCheckMounted = (): (() => boolean) => {
const ref = useRef(true)
useLayoutEffect(() => {
ref.current = true
return () => {
ref.current = false
}
}, [ref])
return useCallback(() => {
return ref.current
}, [ref])
}
// пример использования:
const Child: React.FC = React.memo(() => {
const check = useCheckMounted()
useEffect(() => {
console.log('check1, ', check())
setTimeout(() => {
console.log('check2, ', check())
}, 8000)
}, [check])
return <div>child</div>
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question