We have already discussed the useEffect
topic in one of our previous articles. So, now we will be looking at the 4 best use cases of useEffect
hook that you can implement in your next project.
Prerequisites
Use Cases of useEffect Hook
1. Fetch API
We know that the function inside the useEffect runs only once after initial rendering when an empty array is passed as a dependency. The API that needs to be called only once after the initial rendering can be defined inside the useEffect
hook with an empty array as its dependency.
import React, { useEffect } from "react";
import axios from "axios";
export default function App() {
const fetchData = async () => {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts/1"
);
console.log("response", response);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
console.log("Initial Rendering");
fetchData();
}, []);
return <h1>Use Effect Use Cases</h1>;
}
Output
Here, We tried to fetch the data from https://jsonplaceholder.typicode.com/posts/1 using axios.get()
and we defined the fetch function inside the useEffect and passed an empty array as a dependency. As a result, the function is executed just once after the initial rendering is complete.
2. Real-Time Data Filter
The function runs once after the initial rendering and after every rendering, if the “prop” or “state” provided in the dependency changes. So, a filter function is defined inside the useEffect hook and the text that will be used to filter the array is passed as the dependency. This will make the function run every time the text changes and hence the real-time filter can be executed.
import React, { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
export default function App() {
const [text, setText] = useState("");
const [results, setResults] = useState([]);
let array = ["John", "Chris", "Mike", "Drake", "Harry"];
useEffect(() => {
if (text) {
let filteredtexts = array.filter((name) => name.toLowerCase().includes(text.toLowerCase()));
setResults(filteredtexts);
}
else{
setResults([]);
}
}, [text]);
return (
<div className="d-flex flex-column gap-2 m-4">
<span>Search for Name:</span>
<input
type="text"
onChange={(e) => setText(e.target.value)}
value={text}
/>
<strong>Results:</strong>
{results.length > 0 && results.map((item,i) => <li key={i}>{item}</li>)}
</div>
);
}
Output
Here, we can see, when the user provides input, the array of names is filtered and returns the names that include the text given by the user. This process repeats as long as the user provides the text.
3. Form Validation
We can also perform real-time form validation using the useEffect
hook. For this, we can pass the field value as the dependency and the validation function inside the useEffect
hook.
import React, { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
export default function App() {
const [name, setName] = useState("");
const [error, setError] = useState();
const [checkValidation, setCheckValidation] = useState(false);
const handleValidation = () => {
if (!name) {
setError("This field cannot be empty");
} else if (name.length < 5) {
setError("length should be greater than 5");
} else {
setError("");
}
};
useEffect(() => {
if (checkValidation) {
handleValidation();
}
}, [name]);
return (
<div className="d-flex flex-column gap-2 m-4">
<span>Name</span>
<input
type="text"
onChange={(e) => {
setCheckValidation(true);
setName(e.target.value);
}}
value={name}
required
/>
<span className="text-danger">{error}</span>
</div>
);
}
Output
Here, we triggered the validation function when the user provides some value in the input field and repeat the function as long as the user changes the value. So the validation function applies to the updated value and the suitable error message is displayed.
4. Display Separate Data for Different Options
useEffect
can be used to display separate data for different options. We can store the value of the selected option in a state and pass that state as a dependency in the useEffect
hook. The function that handles the condition to display the corresponding data for the option selected is defined inside the hook.
import React, { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
export default function App() {
const [selectedOption, setSelectedOption] = useState("");
const [result, setResult] = useState("");
const showResult = () => {
switch (selectedOption) {
case "apple":
setResult(
"You selected apple"
);
break;
case "banana":
setResult("you selected banana");
break;
case "mango":
setResult("This is mango")
}
};
useEffect(() => {
showResult();
}, [selectedOption]);
return (
<div className="m-4">
<button onClick={()=>setSelectedOption("apple")}>Apple</button>
<button onClick={()=>setSelectedOption("banana")}>Banana</button>
<button onClick={()=>setSelectedOption("mango")}>Mango</button>
<p>{result}</p>
</div>
);
}
Output
Here, We defined a switch case function inside the useEffect
hook that returns different data according to the option selected by the user. The function repeats when the selected option is changed and hence the data displayed also changes.
Conclusion
In this article, We discussed the 4 best use cases of useEffect
hook that can be implemented in your next project.