-
Notifications
You must be signed in to change notification settings - Fork 0
React Lifecycle Hooks Methods
- Mounting -
static getDerivedStateFromProps(props, state) - Mounting -
componentDidMount() - Updating -
static getDerivedStateFromProps(props, state) - Updating -
shouldComponentUpdate(nextProps, nextState) - Updating -
render() - Updating -
getSnapshotBeforeUpdate(prevProps, prevState) - Updating -
componentDidUpdate(prevProps, prevState, snapshot) - Unmounting -
componentWillUnmount()- Unmounting
clearInterval()
In order to enable this quick reacting and updating, as a developer, you get access to certain built-in events in the React component lifecycle called lifecycle hooks or lifecycle methods. These are opportunities for you to change how the component reacts (or doesn't react) to various changes in your app.
The only required method for a React component to be valid is the render() method which describes what the HTML for the component looks like. There are a whole host of optional methods you can use if you need more control over how the component responds to change.
Whenever a component's state or props are changed, it gets re-rendered on the page (Updating phase). That's the beauty of React components - they're quick to react to changes. Whenever a re-render is triggered, there is a whole host of lifecycle hooks that get called. You can choose to use any of these to decide how your React component should respond to changes.
-
constructoris called because each React Component is still just a JS class
-
static getDerivedStateFromPropscalled just before render, gives us access to any props and state. gets called every time a component renders. It is rarely used as logic before rendering impacts the performance. If you're comparing props from a parent to the state of a child, you can often avoid this by just putting the state in the parent component and handle the comparison logic in the parent. -
renderis invoked, most often returning JSX so that React can insert it into the DOM. -
componentDidMountcalled just after the render method. Used for long-running processes or asynchronous processes such as fetching and updating data. better to render and display something even if not ready, once ready it can re-render and use the now ready API content.
-
getSnapshotBeforeUpdatereturns a 'snapshot' that can be used in the final update lifecycle method,componentDidUpdate. This snapshot allows us to capture things like scroll position, which can possibly change in the small amount of time beforecomponentDidUpdateis invoked. -
static getDerivedStateFromPropsagain available for rare situations where you may need to calculate state changes prior to an update. -
shouldComponentUpdateinvoked just before component re-render. To compare the old and new props and state and prevent unnecessary re-renders: if the changes in state/props don't actually alter the component, no point "repainting" it as it is an unnecessary performance drain. -
rendercalled, returns the JSX for React which uses it to figure out what to display on the page. -
componentDidUpdateafter the component is rendered and updated. It is possible incomponentDidUpdateto take some actions without triggering a re-render of the component, such as focusing on a specific form input.
-
componentWillUnmountonly lifecycle hook at this stage, called just before the component gets deleted, to clear out any stuff set up in componentDidMount. For example, if you had a component that displays the weather data in your home town, you might have set it up to re-fetch the updated weather information every 10 seconds incomponentDidMount. When the component gets deleted, you wouldn't want to continue doing this data-fetching, so you'd have to get rid of what was set up incomponentWillUnmount.
The mounting and unmounting steps are important for ensuring that the React component gets set up and initialized nicely and that when it gets unmounted, it leaves the space it occupied just as it was before: nice and tidy.
In the mounting step, we can set up any special requirements we may have for that particular component: fetch some data, start counters etc. It is extremely important to clean up all the things we set up in the unmounting stage in componentWillUnmount, as not doing so may lead to some pretty nasty consequences - even as bad as crashing your carefully crafted application!
Is possible to use static getDerivedStateFromProps but is rarely used. It is called every time a component is rendered, including the first time.
In the context of mounting, if your intention is to set an initial state for your component, it is preferable for you to do this in the constructor as this.
If your intention is to set state using data from an async request, it is preferable that you do this in componentDidMount.
componentDidMount is also only called once, but immediately after the first render() method has taken place.
That means that the HTML for the React component has been rendered into the DOM and can be accessed if necessary. This method is used to perform any DOM manipulation or data-fetching that the component might need.
Suppose we were building a weather app that fetches data on the current weather and displays it to the user. We would want this data to update every 15 seconds without the user having to refresh the page. componentDidMount to the rescue!
componentDidMount() {
this.interval = setInterval(this.fetchWeather, 15000);
}is the only method in this phase and is to be called immediately before the component is removed from the DOM. It is generally used to perform clean-up for any DOM-elements or timers created in componentDidMount.
In the previous weather API example it would be something like this:
componentWillUnmount() {
clearInterval(this.interval);
}isn't other than a function created to get rid of the interval in this instance. clearInterval()
is possible that a parent component has updated and in re-rendering has passed the same props down to its children. In this case, regular components will still be triggered to update.
This method is for deriving state, meaning you want to modify a component's state based on something in the new props. React's official advice is that you probably don't need this, and in many cases where it seems necessary, there is often a better solution.
it doesn't operate on the state, but returns a Boolean value related on if the component should update or not. Use if for instance you only want a component to update when a value changes past a set threshold.
shouldComponentUpdate(nextProps, nextState) {
return (this.props.myImportantValue !== nextProps.myImportantValue);
}For general optimization of updating, React recommends an alternative - use React.PureComponent instead of React.Component.
The PureComponent does not have access to shouldComponentUpdate, because it instead runs its own version. The PureComponent checks to see if there are any changes to props and state and will only update if it registers a difference between the current and next states.
The render() method is the most familiar one to all React developers. Many Components only need this method.
Right after render, but just before React commits content from its virtual DOM to the actual DOM, the getSnapshotBeforeUpdate method is fired. This method is currently only used to capture information that may be changed after an update. For instance, mouse position and scroll position might be changing rapidly and will change by the time the next lifecycle method is invoked.
This method returns either null or a value that will be passed into the next method, componentDidUpdate.
This method isn't used very often, but it is kind of a look back to the update that just occurred. We will have access to both the current props and previous props, as well as any snapshot info from getSnapshotBeforeUpdate. A common use case for this would be to update a 3rd party library.
componentDidUpdate(previousProps, previousState) {
if (previousProps.height !== this.props.height) {
someChartLibrary.updateHeight(this.props.height);
}
}This method can also be used to interact with the DOM, say by adjusting scroll position.
React has provided us a way to get access DOM elements using something called a ref. You can see an example here:
constructor() {
super()
this.timer = React.createRef()
...
}
...
render() {
const { time, color, className, logText } = this.state
return (
<section className="Timer" style={{background: color}} ref={this.timer}>
...
)
}notice the instance variable being created in the constructor this.timer and consequent ref attribute added to a specific JSX element (<section>).
Once the component mounts, it is possible to access the DOM node <section> using the associated ref attribute. To access the DOM using this.timer, we just need to write this.timer followed by current:
console.log(this.timer.current);
//outputs <section class="Timer" ... > ... </section>
console.log(this.timer.current.style.background);
//outputs the background color, something like rgb(62, 132, 219)
- Mounting -
static getDerivedStateFromProps(props, state)- Mounting -
componentDidMount()- Updating -
static getDerivedStateFromProps(props, state)- Updating -
shouldComponentUpdate(nextProps, nextState)- Updating -
render()- Updating -
getSnapshotBeforeUpdate(prevProps, prevState)- Updating -
componentDidUpdate(prevProps, prevState, snapshot)- Unmounting -
componentWillUnmount()- Element Ref