useEffect hook is used to perform side effects using very few lines of code.
useEffect tells the component what to do after it renders. The most common use case of useEffect is data fetching though we'll not learn how to data fetch in this blog.
There are 3 main variations of this hook:
1. On Every Render
import React, { useState, useEffect } from "react";
export default function App() {
const [name, setName] = useState("");
// on every render
useEffect(() => {
console.log("Rendering on every render");
});
return (
<div className="App">
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
);
}
Here we have an input that has an onChange
event that changes the state of name
every time a word is typed.
Try out in CodeSandBox
As you can see it runs when the page loads and also after every render that happens after that. So it basically runs every time a component is rendered.
But running useEffect on every render can be expensive and can lead to performance issues. Then the second variation of useEffect comes into place.
2. On First Render
import React, { useState, useEffect } from "react";
export default function App() {
const [name, setName] = useState("");
// // on first render
useEffect(() => {
console.log("Rendered only on first render");
}, []);
return (
<div className="App">
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
);
}
Now what it does is it only runs when the component first renders and does not run on every render.
We basically need to add an empty dependency array []
in order for it to only run once when the component is first rendered.
useEffect(() => {
console.log("Rendered only on first render");
}, []);
3. On first render + whenever the dependency changes
import React, { useState, useEffect } from "react";
export default function App() {
const [name, setName] = useState("");
// // on first render + whenever dependency changes
useEffect(() => {
console.log("Renders on first render and whenever the dependency changes");
}, [name]);
return (
<div className="App">
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
);
}
This variation runs when the component first renders and when the passed variable in the dependency array changes. In this case, the passed variable is the name
. Whenever we change something in input it updates the name
state and hence triggers the hook.
It also has a cleanup function that is a little complicated so it is not included in this blog. Will make a separate blog explaining just that.
Resources I used for this blog
Hope you found it helpful and got to learn something❤️