React Native Lifecycle Methods With Hooks Guide
In React Native, you have access to several lifecycle methods that allow you to look into the various stages of a component’s life. These lifecycle methods make it possible to perform tasks such as data fetching, setting up event handlers, and more.
In this article, we’ll take a look at some of the most important lifecycle methods and show how they can be used with hooks.
React Native lifecycle diagram
There are four main life phases in React Native. Actually, I would say there are three life phases and one life phase for Error Handling, which I will tell you about a bit later.
Now, let’s look at the top three most popular and frequently used stages.
Even if not every developer is concerned about that stage, I believe it should be modified, and error handling should be implemented in every project since it may save a lot of time in the future. The stages are split into three phases: render, pre-commit, and commit for the first two (Mounting and Update).
The first part of Mount and Update, known as render, occurs when we perform pure rendering. Our DOM has yet to be affected. We have the option to stop or restart this phase until it’s completed.
The second stage is Pre-Commit, which takes place once we’ve been allowed to read from our React app’s DOM.
React Native Mount
The component mount phase is the first stage of the React component lifecycle when React establishes and enlists our components into the DOM.
Let’s look at some of the feature methods.
You’ll find out when they’re called, what they do, and whether or not you should use them.
React Native constructor
This event is called immediately before a React component is loaded.
It is helpful to use the constructor when initializing components state, binding functions, or event handlers in a component.
We must always call super(props) after setting them to avoid issues when our component’s props are undefined.
React Native static getDerivedStateFromProps
In the Mount and Update lifecycle, this approach is utilized.
This component’s lifecycle method is invoked just before the render method in both situations. It’s convenient when we want to modify the component’s internal state by comparing current props with previous props.
So it’s not simple to utilize this method. You’ll need to know how to do it. It will be simpler to utilize componentDidUpdate or memoization (ensuring that our return value is recompiled when the user’s input changes), but not in every scenario.
React Native render
This event is called immediately after a component has been mounted.
It’s the perfect place to perform initial rendering and check if our page is fully loaded or not.
However, you can’t always depend on this method for this purpose because of the possibility that the user may receive empty updates (due to network errors).
React Native componentDidMount
This event is called after the first render.
It’s usually utilized to fetch data or perform non-UI tasks, such as connecting to an external API.
However, it’s not always appropriate for this purpose because we should not alter the state at any time in componentDidMount (unless it’s related to our React code).
React Native componentWillMount
This method is called just before the first render.
It’s called before React Native performs any rendering or inserts our component into the DOM.
ComponentWillMount is not frequently used because it won’t be called again in most cases after React Native has rendered once (making it useless for many tasks).
React Native update lifecycle methods
The React component lifecycle’s second phase is the update stage.
It occurs when the React application updates the props supplied to a component’s component or internal state.
When a component is updated in React, it works this way and in order:
- static getDerivedStateFromProps
- shouldComponentUpdate
- render
- getSnapshotBeforeUpdate
- componentDidUpdate
Let’s look at what each of them does (the getDerivedStateFromProps and render methods were covered in the Mount section).
React Native shouldComponentUpdate
This method is called when React Native compares a new component to the old version.
It’s our chance to figure out if we want to rerender or not.
We will often use it with conditional logic to determine whether React should update our UI or reuse the current one when possible.
React Native getSnapshotBeforeUpdate
This method is called right before the DOM gets updated, and we can “capture” a snapshot of our component and its children.
This method aims to allow us to prepare for any animations we want to perform with the new props or state values.
React Native componentDidUpdate
This event is called after React Native has finished rendering.
It’s very useful for any cleanup tasks which must happen after the UI updates (such as network requests, animations, etc.).
Since it fires once per update but can capture multiple times, we must check to make sure the DOM only gets altered if necessary (e.g., if the componentDidUpdate method returns false, it means that React Native was not able to patch up our chances in the DOM).
React Native Memoization with Render Callback
Sometimes, we want to check if any of our props or state values have changed before rendering.
It can improve our application’s performance by avoiding expensive work to get the same result.
We’ll need a memoization function that checks if our props and state have been changed before rendering to accomplish this task.
React Native componentWillUpdate (deprecated)
This method is deprecated.
It fires right before the component updates, so it’s also useful for any cleanup tasks which must happen before the UI updates (such as network requests, animations, etc.).
However, since it can’t be used to compare new values with old ones, we won’t use it.
React Native componentWillReceiveProps (deprecated)
This method is deprecated.
It’s similar to componentWillUpdate because it fires right before the component updates due to receiving new props.
We won’t use this one either.
React Native Unmount
The componentWillUnmount method is called when a component is being removed from the Document Object Model (DOM). When this function is invoked, the component has only one method called during this stage: componentWillUnmount.
React Native componentWillUnmount
This method is called just before a component unmounts from the DOM.
Since we may need to perform any cleanup tasks here, we’ll use this method for any additional features which must happen before removing our component from React Native’s virtual tree and updating its state (e.g., removing timers).
We will also call our lifecycle methods in this order inside of componentWillUnmount whenever possible.
React Native Component Error Handling
Exceptions are handled in the exception handling phase, which I’d refer to as an exception handler rather than a lifecycle stage.
This is one of the most essential parts of the component lifecycle.
It is responsible for properly executing the constructor and other aspects of the life cycle method when errors are encountered during rendering, calling constructors, or any other lifecycle method.
Proper error handling is crucial for every React (and other) application. It should be done meticulously because it may save us a lot of time in the future.
In this phase, we have two firing choices:
- static getDerivedStateFromError
- componentDidCatch.
React Native static getDerivedStateFromError
This method is called when an error occurs during rendering.
It allows us to set the state of the component, which will be used as a fallback by static getDerivedStateFromProps if there’s no value passed from parent components.
We can use this method to update the UI with an additional message informing us that something went wrong.
React Native componentDidCatch
This method is called if an error occurs during rendering.
It allows us to catch the caught object which was thrown by getDerivedStateFromError before it’s added to the fallback state.
We will need this object to access the stack trace of where the error occurred, which can be very useful when debugging our application.
React Native lifecycle hooks
There’s no such thing as a “component lifecycle hook” since only React Native methods are tied to specific stages in the component life.
React Native should not be extended with new lifecycle hooks, but instead, we can use three functions (hooks) from the React object:
- useState
- useEffect
- useContext
React Native useState hook
The useState hook returns an array containing the current value and a function to update it.
The state value isn’t stored in “this.state”, so we can access any part of React Native’s virtual tree using this array (or using the object returned by the getDerivedStateFromProps method mentioned above).
React Native useEffect hook
useEffect is similar to componentDidMount because it’s fired after the initial rendering. However, it will be called every time any of its dependencies change - not just when the component mounts into the DOM.
Due to this nature, we can’t technically rely on React Native’s virtual tree to store the react-redux Provider instance. If we wanted to force a rerendering of our component, there’d be no other way but to actually change the state.
React Native useContext hook
It’s obvious that any React native components can’t access “this.context”. However, they can access global context using the getContext() method.
It’s worth noting that each component can access context provided by its ancestors, but not the ones from the parents of those ancestors.
The useContext hook returns a function that accepts a context object and returns whatever is needed (in most cases, it would be an object with the Provider and Consumer instances).
If you need help with React Native development, please don’t hesitate to contact us. We have a team of experienced developers who would be happy to assist you.
Thank you for reading,
Radek from Duomly