Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for useEffect - React Hooks Series
Pratap Sharma
Pratap Sharma

Posted on • Edited on • Originally published atpratapsharma.io

     

useEffect - React Hooks Series

Welcome back to the series ofReact Hooks. In part one of the series, I wrote about the useEffect react hook.

Series path

What isuseEffect hook?

TheuseEffect hook lets you perform side effects in functional components.

Few examples of side effects

  • Data fetching
  • Setting up a subscription
  • Manually changing the DOM in React

If you are familiar withReact class lifecycle methods, you can think ofuseEffect hook ascomponentDidMount,componentDidUpdate andcomponentWillUnmount combined.

What doesuseEffect hook do?

By using thishook, you let React know that your component needs to perform somethingafter rendering of the component. React will remember the function which you passed and react call itafter performing the DOM updates.

In thiseffect we can do many things like setting document title, fetch some data from an API, setting event listeners.

Does useEffect run after every re-render?

Yes! By default, the effect runs both after the first render and after every update of the component. Rather than thinking in terms ofmounting andupdating, you might find it simpler to think thateffects happenafter render. Reactguarantees the DOM has been updated by the time it runs the effects.

Example

Let's change the document title for better understanding.

Using class component

importReactfrom"react";classExampleComponent{//After renderingcomponentDidMount(){document.title="Updating the title in componentDidMount";}//After updatingcomponentDidUpdate(){document.title="Updating the title in componentDidUpdate";}render(){return<div>Setting the title</div>;}}exportdefaultExampleComponent;
Enter fullscreen modeExit fullscreen mode

Using functional component

importReact,{useEffect}from"react";constExampleComponent=()=>{useEffect(()=>{document.title="Setting title using useEffect";});return<div>Setting the title using useEffect hook</div>;};
Enter fullscreen modeExit fullscreen mode

Infunction component, you have to define oneuseEffect function instead ofcomponentDidMount andcomponentDidUpdate.

Getting deeper

Now we know whatuseEffect is. Let us try to understand it deeper.useEffect function accepts two-parameter. i) A function which gets called on every update/re-rendering. ii) An array of dependencies value on which the function has to get called.

1. The useEffect below will always get called on rendering and updating of the component.

useEffect(()=>{console.log("I will be called each time the component renders and re-renders");});
Enter fullscreen modeExit fullscreen mode

2. The useEffect below will get called only once. i.e. the first time it renders. It is equivalent tocomponentDidMount. The second parameter[] is called the dependencies array. An empty array means no dependency.

useEffect(()=>{console.log("I will be called only once when the component is mounted");},[]);
Enter fullscreen modeExit fullscreen mode

3. The useEffect below will get called each time the value ofname is changed. It is likecomponentDidUpdate.

useEffect(()=>{console.log("I will be called first when the component is mounted and each time the name is changing");},[name]);
Enter fullscreen modeExit fullscreen mode

4. If we want to do any clean-ups before the component is unmounted.

useEffect(()=>{// some tasksreturn()=>{console.log("I do cleanups");console.log("will first run on component mount then, will run before useEffect and lastly before unmounting");};});
Enter fullscreen modeExit fullscreen mode

Wrapping up

I want to thank you for going through the part two of my React Hooks series, in case you missed part one please check it out here(hyperlink)

If you have any questions, comments, corrections I would look forward to it. Thank you for making it this far.

Series path

💌 If you'd like to receive more tutorials in your inbox, you can sign up for the newsletterhere.

Top comments(4)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
ardyfeb profile image
Ardy Febriansyah
  • Location
    Padang, Indonesia
  • Work
    DevOps Engineer at Juabali
  • Joined

The second should becomponentDidUpdate

CollapseExpand
 
pratap2210 profile image
Pratap Sharma
I am a Software Engineer with 6+ years of experience in building and deploying web applications using varying tech stacks. My expertise lies in the frontend, backend and mobile apps.
  • Email
  • Location
    Pokhara, Nepal
  • Education
    Mizoram University
  • Work
    Lead Engineer at Rippey AI
  • Joined

Thank you@ardyfeb . I have update the same.

CollapseExpand
 
danielsarmiento profile image
Daniel
Junior Software Engineer at TravelPerk.
  • Email
  • Location
    Barcelona, Spain
  • Education
    George Mason University, Universidad Carlos III de Madrid
  • Work
    Software Engineer at TravelPerk
  • Joined

Nice, short and straight to the point. Thank you for this series, Pratap!

But if you could update the first snippet like Ardy commented it would help a lot of other readers 🙏

CollapseExpand
 
pratap2210 profile image
Pratap Sharma
I am a Software Engineer with 6+ years of experience in building and deploying web applications using varying tech stacks. My expertise lies in the frontend, backend and mobile apps.
  • Email
  • Location
    Pokhara, Nepal
  • Education
    Mizoram University
  • Work
    Lead Engineer at Rippey AI
  • Joined

Thank you@danielsarmiento . I have updated the same.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a Software Engineer with 6+ years of experience in building and deploying web applications using varying tech stacks. My expertise lies in the frontend, backend and mobile apps.
  • Location
    Pokhara, Nepal
  • Education
    Mizoram University
  • Work
    Lead Engineer at Rippey AI
  • Joined

More fromPratap Sharma

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp