React introduced hooks in versino 16.8.
What does a hook do?
Basically a hook let you use state and some other features in React, without writing a class. Basically you perform some sort of side actions/effects in the function components itself.
We can make this equation from React class lifecycle methods.
useEffect = componentDidMount + componentDidUpdate + componentWillUnmount
There are two different kinds of side effects. One of those type requires a cleanup afterwards and the other one doesn’t.
Effects Without Cleanup
Performing activities like logging of some variable doesn’t require a clean up. That means you run some code and that’s it. It’s not going to change anything else in the app. So, you can run it and then forget about it.
In this post, How states work in React?, I have a lifecycle methods example.
So, basically what you can do using these two methods in a class…
...
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
...
… can be done by using the hook in a function component:
import React, { useState, useEffect } from 'react';
...
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
...
You need to import useEffect and useState in order to use it.
useEffect removed the redundancy of writing the same code twice as we did in componentDidMount and componentDidUpdate methods.
functions hook use rule useEffect useState