DEV Community

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

Posted on

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 :-)

Discussion (0)