Table of Contents
Memory Leak
Memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations. Sometimes, we get a warning about memory leak in our React applications such as Can’t perform a React state update on an unmounted component. We shouldn’t update state in an unmounted component. For example, we are fetching data at the first mouting to update component states, but we immediately navigate to another page or take other actions to make the component unmounted so state updating becomes unuseful. That’s a reason why React warns the message.
A block of code related to that example:
const Component = () => {
const [data, setData] = useState([])
useEffect(() => {
fetchData().then(data => setData(data))
}, [])
return (
<>
// render component
</>
)
}
The problem is that while fetchData was running, suddenly the component was unmounted. When Promise is settled, callback handler will be executed, a part of memory has been reserved for storing the results returned from the API (perform setData), so that’s useless and superfluous.
Solve the problem
- Solution 1: use a flag to check whether the component is unmounted or not
const Component = () => {
const [data, setData] = useState([])
useEffect(() => {
let isUnmounted = false
fetchData().then(data => {
if (isUnmounted) return
setData(data)
})
return () => {
isUnmount = true
}
}, [])
return (
<>
// render component
</>
)
}
- Solution 2: use AbortController to cancel request
const Component = () => {
const [data, setData] = useState([])
useEffect(() => {
const controller = new AbortController();
// fetch data
axios.get('/', {
signal: controller.signal
}).then(function(data) {
setData(data)
});
return () => {
controller.abort();
};
}, [])
return (
<>
// render component
</>
)
}
Some memory leak cases in React
There are some cases that make memory leaks in Reactjs:
- Don’t clean up subscription when unmounting
- Don’t clean DOM event when unmouting
- Don’t clean timer when unmouting