DEV Community

Yongkang Cheng
Yongkang Cheng

Posted on

React: useEffect

Today's topic is to learn useEffect in React.

In my point of view, the useEffect helps you call a function in a proper time, so that you don't need to write an infinite loop to monitor...
Since the useEffect also calls the function when the component is first time rendered and also call another function when the component is being removed, we can do a lot based on it. It is very useful in anyways.
Before start, make sure that you are familiar with the useState component.

Import Package

import { useEffect } from 'React';
Enter fullscreen mode Exit fullscreen mode

Syntax

useEffect(function, [dependency array]);
Enter fullscreen mode Exit fullscreen mode
  • The first param is a function which would be automatically called, and the function should return the "uninstall" function to clean up the memory if neccessary.
  • The second param is an array that contain the variables you want to monitor. Once the parameter is changed, the function (first param) will be automatically called. An empty array means it does not monitor any variable.

A brief example:

useEffect(() => {
    do_something;
    return uninstall_function;
}, [variable_to_be_monitored]);
Enter fullscreen mode Exit fullscreen mode

Example

First we make a simple click button screen without the useEffect:

import React, { useState, useEffect } from 'react';
import './App.css';


function MyButton({ updateFunc }) {
    return (
    <div>
        <button onClick={updateFunc} className='button'> Click Me </button>
    </div>
    );
}

function App() {
    const [count, setCount] = useState(0);

    return (
    <div className="App">
        <p>This is a counter</p>
        <p>Currently the count is {count}</p>
        <MyButton updateFunc={() => { setCount(count + 1); }}/>
        <MyButton updateFunc={() => { setCount(count - 1); }}/>
    </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

And here is what the screen looks like:

Image description

Then we add the useEffect to log to the console each time we click the button:

import React, { useState, useEffect } from 'react';
import './App.css';


function MyButton({ updateFunc }) {
    return (
    <div>
        <button onClick={updateFunc} className='button'> Click Me </button>
    </div>
    );
}

function App() {
    const [count, setCount] = useState(0);
    useEffect(() => {
        console.log(`button clicked. count: ${count}`);
    }, [count]);

    return (
    <div className="App">
        <p>This is a counter</p>
        <p>Currently the count is {count}</p>
        <MyButton updateFunc={() => { setCount(count + 1); }}/>
        <MyButton updateFunc={() => { setCount(count - 1); }}/>
    </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

And you can see the console of the webpage. It is like this:

Image description

Another Example

Here is the example updating the "online time" every second using a timer (if you don't know a timer, please search for setInterval...). In this time, the useEffect will help clear the timer when the component is removed.

import React, { useState, useEffect } from 'react';
import './App.css';

function App() {
    const [sec, setSec] = useState(0);

    useEffect(() => {
        // define the timer
        const timer = setInterval(() => {
            // insert a function into the `setSec` to avoid name space issues
            // setSec(sec + 1);
            setSec(prevSec => prevSec + 1);
        }, 1000);
        // return the cleaning function
        return () => {
            clearInterval(timer);
        }
        // the empty array below makes it only call the 
        // function once when the component is loaded
    }, []);

    return (
    <div className="App">
        <p>You stayed alive for {sec} seconds.</p>
    </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

And the result is like the image below, and it is continuously updating with a minimum CPU workload.

Image description

Top comments (0)