How to do componentWillUnmount in React Native with hooks

Ats
2 min readOct 1, 2023

--

I wanted to do something similar to componentWillUnmount in React Native with hooks, not class components. This is not exactly the same as componentWillUnmount but it is enough for me.

Photo by Milad Fakurian on Unsplash

Background

Currently, I’m using the following versions.

  • Expo: 48
  • react-navigation: v6

I wanted to check and update a state before moving to the next screen in my React Native app. Initially, I did some experiments with plain useEffect in the screen like below.

useEffect(() => {
return () => {
...check and update state here...
}
}, [])

But it works like componentDidUnmont . Because of that, the components depending on the state flick for a second. Then I was looking for a solution.

What I did

I used the event listener provided byReact Navigation . The beforeRemove event works well in my use case.

I would say the useFocusEventhook works fine in most cases.

But, in my use case, thefocus event didn’t work well. I guess rerendering would happen and the event would triggered a few times when opening the target screen. I could fix the re-rendering issue but it depended on a third-party library so I decided to go with my custom event listener.

The following code snippet is my custom hook for the event listener.

export const useDoSomethingOnRemoveScreen = () => {
const navigation = useNavigation();

useEffect(() => {
const unsubscribe = navigation.addListener('beforeRemove', () => {
...check and update state here...
});

return unsubscribe;
}, [navigation]);
};

Thanks to the hook, My state is checked and updated before the next screen component is mounted, and the flicking has disappeared.

That’s it!

--

--

Ats
Ats

Written by Ats

I like building something tangible like touch, gesture, and voice. Ruby on Rails / React Native / Yocto / Raspberry Pi / Interaction Design / CIID IDP alumni

No responses yet