useEffect Hook
What is the useEffect Hook?
The useEffect Hook is a function that also accepts another function inside of the array.
This hook runs when something changes.
It looks the same as the useState hook, it is also an array with two items inside of it.
The first item is the function you want to run.
The second item is an array of things like variables or props that you want to change.
You can use useEffect when something changes that is relatively small.
Example:
import { useState, useEffect } from 'react'
function Example() {
const [count, setCount] = useState(0)
useEffect(() => {
document.title = `You clicked ${count} times`
})
return (
<div>
<p> You clikced {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
)
}
In the above example, you tell React that that component needs to do something after render. IT will then remember the function you passed, which you can call the effect. It then calls it later after performing the needed DOM updates.
Interesting things to point out
It can be compared to working with the class lifecycle methods
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
.You can use the useState hook in combination with the useEffect hook, but it is not necessary.