Understanding React Hooks - UseEffect

Understanding React Hooks - UseEffect

Checking my second todo in my understanding React Hooks series we would be talking about a cool react hook called UseEffect. As compared to the first react hook in the series UseState which handles state management in react, UseEffect on the other hand is all about React life-cycle methods but in this case, in functional React components.

UseEffect is used for many functions such as running a function or piece of code either on DOM mount or state change, fetching data from APIs, live-updating data, and props when there is state or prop changes. They are regarded most times as side effects in our application which run after the render has been completed. In the same way in our last tutorial on useState, we advised triggering useState after an event, in UseEffect we can trigger the function execution by changing the state of the dependency array.

UseEffect function consists of three parts, the function itself to be executed, a dependency array, and a cleanup function for things that needs unmounting. In most cases, the cleanup function is not used unless necessary so won't be discussed in this tutorial. The function is dependent on its use, ranging from fetching API data to other forms of computation. The dependency array is used to regulate or schedule when we want the function to run. It can be empty which is default or be a state variable or many state variables in the application.

When the array is empty it means that the UseEffect function will render once after the DOM mounts, such a great use for fetching dynamic data for page display. When the array has a state variable it means that the function will run only when the state variable changes, this will be helpful in terms of validating input and live updates.

Let's get down to some examples to see the UseEffect function at work.

In our first example, we would be fetching data (posts) from a free fake REST API and using the data to render the page.

import {useEffect, useState} from 'react'

const Example = () => {
    const [posts, setPosts] = useState([])

    useEffect(async () => {
       const res = await fetch("https://jsonplaceholder.typicode.com/posts")
       const data = await res.json()
       setPosts(data)
    }, [])

    return (
        <>
         <div>
            <h2>List of Todos</h2>
        </div>
        <div>
            {posts.map((ele) => {
                return(
                    <div key={ele.id}>
                        <h4>{ele.title}</h4>
                        <h5>{ele.body}</h5>
                    </div>

                )
            })}
        </div>
</>

    )
}
export default Example;

In the code above, the UseEffect function was called once, and immediately after the DOM mounts, the function fetches data from an API and renders the data on the page.

To make the page cooler, we would be fetching individual posts using the Id number which we would be inputted from the page.

import {useEffect, useState} from 'react'

const Example = () => {
    const [id, setId] = useState('');
    const [post, setPost] = useState({});

    useEffect(async () => {
        const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
        const data = await res.json()
        setPost(data)
     }, [id]);

    return (
        <>
         <div>
            <h2>Get Todo</h2>
            <input type='number' name='id' placeholder='input todo Id'
             aria-controls='true' onChange={(e) => setId(e.target.value)}/>
        </div>

        <div>
            <h2>{post.title}</h2>
            <h5>{post.body}</h5>
        </div>
        </>
    )
}
export default Example;

This code above is using UseEffect to perform a live update of posts on the page using the id state variable. The UseEffect function which fetches the data runs whenever there is a change in the id from the input form. Very 😎😎 right...

UseEffect can be used in many applications, and a component can have more than one UseEffect function with different dependency arrays, but be careful with the dependency array to avoid the unusual running of a function.

Thanks for reading to the end, also check out my UseState tutorial if you missed itπŸ™‚πŸ™‚...

Β