React Hooks — useEffect

“The useEffect Hook allows developers to perform side effects in our Components. Some examples of side effects are fetching data, directly updating the DOM, and timers.”¹
[1] https://www.w3schools.com/react/react_useeffect.asp
useEffect is one of the most important concepts to mastering React. Best practice is using useEffect asynchronously to avoid unnecessary complexity and introducing errors to your code. In order to use useEffect, we must initialize the Hook by importing it at the top level of our component; i.e
import React, {useEffect, useState} from 'react';
The Component will be rendered first, then useEffect will be called. Every time our component re-renders, useEffect will also run.
The order of operations for our Component is:
render > useEffect > setState > re-render > useEffect
We can control when the useEffect runs by adding a second argument of a dependencies array:
useEffect (() => {
console.log("UseEffect called");
//fetch
}, [] //dependency array if empty, only runs once!
If we add arguments to the array, it will check the variable for renders, and then re-run the useEffect based on changes:
useEffect(() => {
console.log("UseEffect called");
//fetch
}, [count]
I created a single page application React project (Medicinal Wellness Center), where i created my own REST API with JSON Server that includes an array of objects where I used useEffect hook to fetch the data in my db.json file when the app first loads. First, I declared the variables strains and searchTerm and their setter functions setStrains and setSearchTerm, respectively. I assigned strains to an empty array. The second .then() is a promise used to deal with the asynchronous task of updating the empty array of strains by using the setter function of setStrains to update strains with the fetched data at our localhost.
const [strains, setStrains] = useState([]);const [searchTerm, setSearchTerm] = useState("")useEffect(() => {fetch("http://localhost:3000/strains").then((r) => r.json()).then((strains) => setStrains(strains));}, []);
This allows the user to see all the data when the app first loads. The Medicinal Wellness Center is an application where users can enter their diagnoses in the search box, and cannabis strains that can manage the diagnosis will be filtered then mapped through to appear on the home page. The populated strains will also have information pertaining to the name, strain, species, an image, top effect, flavor and aroma, THC percentage, and rating.
In my opinion, useEffect is the best part of React Hooks. useEffect provides reusability, readability, and testability. useEffect also helps reduce clutter of the components life cycle and also separates different logic. Holding state and useEffect in a parent component allows me to pass data via props to child components. This was beneficial while building the Medicinal Wellness Center because I was able to reuse data without having to fetch multiple times, it make my code a lot cleaner and saved time as well. Adding a second argument to useEffect can also control when side effect code will run.
No dependencies array:
useEffect(() => {})
Run the side effect every time our component renders (whenever state or props change).
Empty dependencies array:
useEffect(() => {}, [])
Run this side effect only the first time our component renders.
Dependencies array with elements in it:
useEffect (() => {}, [variable1, variable2])
Run this side effect any time the variable(s) change.
-Till next time.