Life Cycle Methods vs React Hooks




Today I am going to talk about life Life Cycle Methods vs React Hooks. First, let me introduce React hooks. React 16.8.0 is the first release to support to support hooks. Hooks solve a wide variety of seemingly unconnected problems in React that we’ve encountered before. Now we are able to do almost everything in the functional components like class components. Hooks are very easy to learn and use. There are many react hooks. Such as useState, useEffect, useReducer, useContext and etc. In this post, I am going to talk about useEffect and how it is going to use instead of componentDidMount, componentDidUpdate and componentWillUnmount.

The Effect Hook lets you perform side effects in function components.


  • componentDidMount() vs useEffect()
The componentDidMount() method runs after the component output has been rendered to the DOM.
We can use it like below:


Below showing you how to use useEffect instead of comonentDidMount().



By using this Hook, you tell React that your component needs to do something after render at only once. React will remember the function you passed, and call it later after performing the DOM updates. If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. 

  • componentDidUpdate() vs useEffect()

componentDidUpdate() runs when the props or states has changed. Below is the way to handle useEffect() to this.


First effect, component will update only when the "bodyValue" has been changed. If you use this optimization, make sure the array includes all values from the component scope (such as props and state) that change over time and that are used by the effect. Otherwise, your code will reference stale values from previous renders. Second effect, component will update when there are any props or states have been changed. It is equal to componentDidMount() + componentDidUpdate(). 

  • componentWillUnmount() vs useEffect()
This method fires just a moment before the component unmount. Below is the way to use componentWillUnmount().



Below is the way to how to use the useEffect().



We don’t have to return a named function from the effect. We called it cleanup here to clarify its purpose, but you could return an arrow function or call it something different.

  • componentDidMount() + componentDidUpdate() + componentWillUnmount() vs useEffect()


Above is the way to use three component life cycle in one method (useEffect). Now you have understand how powerful are React hooks and how easy to use it.

Comments

Popular posts from this blog

API Guidlines (PayPal Standard)