React: useEffect
Published: 2024-07-12 04:12:31

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
```javascript
import { useEffect } from 'React';
```

## Syntax
```javascript
useEffect(function, [dependency array]);
```
* 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:
```javascript
useEffect(() => {
    do_something;
    return uninstall_function;
}, [variable_to_be_monitored]);
```

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

```javascript
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;
```
And here is what the screen looks like:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1hz7giwdm9w1fmvsrzt9.png)

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

```javascript
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;
```

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6lf41v7ec6zcw71xl069.png)

## 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.

```javascript
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;
```

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wt0o1r1jtjzf1ozb8u0y.png)