How to cleanup store on component unmount?
See original GitHub issueI couldn’t find a way to cleanup my store on component unmount. I’m using the Zustand way mentioned in the docs for handling stores with createTrackedSelector
, but it seems like this hook keeps the reference to the store forever without providing a way to avoid memory-leaks.
const useMyStore = createTrackedSelector(MyZustandStore)
const MyComponent = () => {
const store = useMyStore()
useEffect(() => {
return () => {
// how can I destroy my store on cleanup?
}
}, [])
return <button onClick={store.increase}>{store.count}</button>
}
calling MyZustandStore.destroy()
doesn’t help; neither does re-assigning the store with another value.
Issue Analytics
- State:
- Created a year ago
- Comments:6 (3 by maintainers)
Top Results From Across the Web
Clean redux state when component unmount cancel all ...
Clean redux state when component unmount cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
Read more >Understanding React's useEffect cleanup function
React's useEffect cleanup function saves applications from unwanted behaviors like memory leaks by cleaning up effects.
Read more >How to Cleanup Side Effects in React | by ReactOne - Medium
The solution is to cancel any side effect if the component unmounts, let's see how to do that in the next section. 2...
Read more >React useEffect cleanup: How and when to use it
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....
Read more >Why you should always Cleanup Side Effects in React ...
Why should you cleanup when a Component unmounts? · To avoid memory leaks · To optimize our applications for a good user experience...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
That will become like a local state, but something like the following.
I used
useRef
instead ofuseState
, because it’s slightly more lightweight.This is nice. Thanks for sharing!