DEV Community

Cover image for React 101 - part 7: useEffect
Eric The Coder
Eric The Coder

Posted on

7 3

React 101 - part 7: useEffect

After my Javascript series: https://dev.to/rickavmaniac/javascript-my-learning-journey-part-1-what-is-javascript-role-and-use-case-49a3

I am now ready to begin my React learning journey :)

Click follow if you want to miss nothing. I will publish here on Dev.to what I learn from my React course the day before.

Without further ado here is a summary of my notes for day 7.

useEffect Hook

Since we no longer use React class component how we will be able to use lifecycle like componentDidMount and componentWillUnmount?

The React replacement for lifecycle method is a Hook call useEffect.

useEffect Hook runs after every render (by default), and can optionally clean up for itself before it runs again.

Rather than thinking of useEffect as one function doing the job of 3 separate lifecycles, it might be more helpful to think of it simply as a way to run side effects after render – including the potential cleanup you’d want to do before each one, and before unmounting.

To understand useEffect, let revisit our Counter component.

import React, { useState } from 'react'

export function Counter() {
    const [count, setCount] = useState(0)
    const handleClick = () => setCount(count+1)

    console.log(count)
    return <div>
        <h1>Counter Component</h1>
        <p>{count}</p>
        <button onClick={handleClick}>+</button>
    </div>
}
Enter fullscreen mode Exit fullscreen mode

Let say we want to change the page title every time the count state change. How to do that? useEffect!

First we need to import useEffect from 'react'
Second we call the useEffect() that return a function

import React, { useState, useEffect } from 'react'

export function Counter() {
    const [count, setCount] = useState(0)

    useEffect(() => document.title = `Counter ${count}`)

    const handleClick = () => setCount(count+1)

    console.log(count)
    return <div>
        <h1>Counter Component</h1>
        <p>{count}</p>
        <button onClick={handleClick}>+</button>
    </div>
}
Enter fullscreen mode Exit fullscreen mode

With that new code, every time the state of my component change. The useEffect() is call.

If we want to change the title only when the count state change and not every time anything change, we can add a parameter to useEffect: useEffect(callback, [array of variables to watch])

import React, { useState, useEffect } from 'react'

export function Counter() {
    const [count, setCount] = useState(0)

    useEffect(() => document.title = `Counter ${count}`, [count])

    const handleClick = () => setCount(count+1)

    console.log(count)
    return <div>
        <h1>Counter Component</h1>
        <p>{count}</p>
        <button onClick={handleClick}>+</button>
    </div>
}
Enter fullscreen mode Exit fullscreen mode

If we execute the useEffect with noting in the array: useEffect(callback, []) then the callback will be execute only on first load. So that will literally do the same as componentDidMount() lifecycle

Example this can be handy to set a timer

import React, { useState, useEffect } from 'react'

export function Counter() {
    const [count, setCount] = useState(0)
    const handleClick = () => setCount(count => count + 1)

    useEffect(() =>  { 
        const timer = window.setInterval(() => { 
            setCount(count => count + 1)
        }, 1000)
        return () => clearInterval(timer)
    }, [])

    return <div>
        <h1>Counter Component</h1>
        <p>{count}</p>
        <button onClick={handleClick}>+</button>
    </div>
}
Enter fullscreen mode Exit fullscreen mode

If we want to cancel the timer when the component is unmount like componentWillUnmount() we just have to place a return function at the end of useEffect.

This useEffect return function is execute each time the component unmount. Think at this return function like a cleaning code when the component unmount.

Conclusion

That's it for this course. I know there a lot to be learn, but this course was React 101 and I think I reach my goal to learn the very basic. My advice is practice what you have learn so far and when you feel comfortable with the basic you can reach for more :-)

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Explore this insightful post in the vibrant DEV Community. Developers from all walks of life are invited to contribute and elevate our shared know-how.

A simple "thank you" could lift spirits—leave your kudos in the comments!

On DEV, passing on wisdom paves our way and unites us. Enjoyed this piece? A brief note of thanks to the writer goes a long way.

Okay