Let’s look at the react component lifecycle and how it can be replaced with hooks.
Want’s to learn React Hooks?
componentDidMount()
This method is called when the component has finished rendering for the first time. It is only called once throughout the lifecycle once after the component has finished mounting.
Using Hooks:
componentDidUpdate( )
This method is called multiple times in app lifecycle. It is execute immediately after updating occurs. This method is not called for the initial render.
There are two ways to handle,
1. Call hooks on every render
You can see if the following example the second argument in the hooks is blank, it means it will execute on every render.
Using Hooks:
2. Call hooks when specific props/dependency are changed
To implementation this, we need to pass the second argument to useEffect and it will be automatically triggered whenever that dependency is changed.
Using Hooks:
ComponentWillUnmount( )
This method will be called when the component is unmounted and it will be called only once in the component’s lifecycle.
Using Hooks:
Return a callback in useEffect’s callback argument and it will be called before unmounting.
shouldComponentUpdate( )
This method is called every time the component is going to render where you can return true/false whenever you have to render the component or avoid rendering.
But since Hooks can be only used in functional component, and functional component internally handles the shouldComponentUpdate() method for use. You can already achieve this on the component level using React.PureComponent or React.memo. For preventing rerendering of the child components.
Using Hooks:
By default, it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.
getDerivedStateFromProps( )
getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
Using Hooks:
Lifecycle method which are not replaced
Following are some of the methods that do not have any lifecycle method replacement for hooks according to the react documentation:
componentDidCatch ( )
getSnapshotBeforeUpdate( )
getDerivedStateFromError ( )
What Next!
Connect Us —
KPITENG — DIGITAL TRANSFORMATION
www.kpiteng.com | hello@kpiteng.com