React hooks – useEffect hook explained Part 1
Hi, the React hooks are the new addition in React 16.8 and permit us to use a state and other React features without writing a class.
Note: you can find the code of this post in my GitHub account.
The useEffect hook let us to perform side effects like:
- data fetching
- subscriptions
- manually changing the DOM
We can think of useEffect as a componentDidMount, componentDidUpdate and componentWillUnmount combined. The idea is do not replicate code between lifecycle methods.
We going to see two common types of side effects in React components:
1
Effects without cleanup
If we want to execute additional code after React has updated the DOM, that doesn’t require cleanup (because we can run them and immediately forget about them), like for example:
- Network requests
- Manual DOM mutations
- Login
Let’s see an example of useEffect
// Dependencies
import React, { useState, useEffect } from 'react';
// Styles
import './App.css';
function App() {
// Local state
const [count, setCount] = useState(0);
// useEffect -> You tell React that your component needs to do
// something after render.
// Also useEffect by default run "after every render"
useEffect(() => { // This arrow function as our "effect", when React renders our component, it will remember the effect we used.
console.log('Enter useEffect'); // useEffect runs both after the first render and after every update
});
return (
<div className="App">
<p>Clicked times { count }</p>
<button
type="button"
onClick={() => setCount(count + 1)}
>
Click me!
</button>
</div>
);
}
export default App;
Because useEffect is inside the scope of our function component, we can access to all the variables, local state and props that our component have.
So, let see our next example:
// Dependencies
import React, { useState, useEffect } from 'react';
// Styles
import './App.css';
function App() {
// Local state
const [count, setCount] = useState(0);
// useEffect runs both after the first render and after every update
useEffect(() => { // This arrow function as our "effect"
// useEffect it will remember the effect we used
// useEffect runs after every update
console.log('Clicked times ->', count); // each effect “belongs” to a particular render
});
return (
<div className="App">
<p>Clicked times { count }</p>
<button
type="button"
onClick={() => setCount(count + 1)} // Every time we re-render, we schedule a different effect, replacing the previous one
>
Click me!
</button>
</div>
);
}
export default App;
Note: This example doesn’t require cleanup (because we can run them and immediately forget about them).
I will continue in the next post with the “side effects with cleanup”.
By Criss.