DEV Community

loading...
Cover image for Let's break down the useEffect hook.

Let's break down the useEffect hook.

Sachin Chaurasiya
A passionate developer who love to connect with people to share ideas and knowledge.
Updated on ・3 min read

Hello Learners,

Today is the 3rdDay of #8DaysOfReactHook.
In This post will see the breakdown of the useEffect hook.

What is useEffect hook?

useEffect hook is a special function that lets us run the side effect from the functional component. It is a close replacement for ComponentDidMount, ComponentDidUpdate and ComponentWillunmount.

Syntax of useEffect

Alt Text

let's see an example

Alt Text

Let say we have a contact component and we want to change the title of the page when the contact component renders to the DOM. so for this use case, we have used the useEffect hook. we have passed two arguments to the useEffect hook that is a callback function and empty array [].

in the callback function, we are setting the document title as our custom title. Now we want this change only once i.e when the component renders to the DOM. that's why we have given empty Array ([]) as a second argument.

useEffect with Some Condition

 import React,{useEffect,useState} from "react"
 import Axios from "axios"

 const SinglePost=(props)=>{
 const id=props.id;
 const [post,setPost]=useState({}) 


 useEffect(()=>{
  Axios.get(`https://myposts.com/posts/${id}`)
  .then((res)=>setPost(res.data)) 
  .catch((err)=>console.log(err))

 },[id]) 

  return (
   <div>
    <h1> {post.title} </h1>
    <hr/>
    <p> {post.body} </p>
    </div>
  )
}

export default SinglePost;
Enter fullscreen mode Exit fullscreen mode

Let say we want to fetch a single post from some endpoint. Above code, we have created one component i.e SinglePost and passing id prop to fetch post for that id.

we have passed two arguments to the useEffect hook one is a callback function that will perform the side effect (i.e fetching post from endpoint) and another is a dependency array that includes `id`. which means whenever `id` changes useEffect will run the callback function to fetch the post and set the new state.

Now as soon as the `SinglePost` Component renders to the DOM useEffect will fetch the post and will set the State.

useEffect with Cleanup

Now, let say we want to listen for some event and log the information into the console. but what if we remove the component and still trying to listen to the event, it will throw an error.

To solve this in-class component we have the ComponentWillUnmount lifecycle method.

but what about the functional component? how can we solve this type of issue?

To rescue from this useEffect allow us to return a cleanup function from the callback function when the component will unmount from the DOM.

Let see an example,
Axios comes with a cancel token to cancel the request when not needed.
in this example, we are fetching posts from some endpoint and if there is some occurred component will unmount so to prevent memory leak will return a cleanup function which will cancel the request.

  useEffect(() => {
    const source = axios.CancelToken.source()

    const fetchPosts = async () => {
        try {
            await Axios.get('/posts', {
                cancelToken: source.token,
            })
            // ...
        } catch (error) {
            if (axios.isCancel(error)) {
            } else {
                throw error
            }
        }
    }

    fetchData()

    return () => {
        source.cancel()
    }
}, [])
Enter fullscreen mode Exit fullscreen mode

There are many use Cases for useEffect hook and covering those in one post is not possible. so I have highlighted some use cases so that you can get a better overview of the useEffect hook.

If you have Doubt or Suggestions please let me know in the comment section.

Thank you for reading.

Connect with me LinkedIn

Discussion (0)

Forem Open with the Forem app