How To Listen For State Changes In React

How to Listen for State changes in React

Let me help you learn how to listen for state changes in React through this article. There is a very simple method that I will show you. Check out the information right now.

Listen for state changes in React

Hooks were first introduced in React version 16.8 in 2019. One of them is the useEffect hook. In React, we use the useEffect to listen for changes.

Syntax:

useEffect(<function>, <dependencies>)

Parameters:

  • <function>: Is where you write the statements that handle the logic of your program.
  • <dependencies>: The function that we declare in the first parameter will be executed when one of the variables ​​in <dependencies> changes.

Example program

To illustrate, here is a small example for you. Take a look at this program:

.container {
  	margin-top: 20px;
}

.btn {
  	margin-left: 20px;
}

.light {
    height: 150px;
    width: 150px;
    border-radius: 100px;
    text-align: center;
    margin-top: 15px;
}
import './App.css';
import {useEffect, useState} from 'react';

const App = () => {
    const [lightSwitch, setLightSwitch] = useState('Off');
    const [press, setPress] = useState(0);

    let style = {};
    if (lightSwitch === 'On') {
      	style = { 'background-color': 'yellow', color: 'black' };
    } else {
      	style = { 'background-color': 'black', color: 'white' };
    }

    useEffect(() => {
        if (press % 2 === 0) {
          	setLightSwitch('Off');
        } else {
          	setLightSwitch('On');
        }
        console.log('Press the light switch');
    }, [press]);

    return (
        <div className='container'>
            <button 
              type="button" 
              className="btn btn-primary" 
              onClick={() => setPress(press + 1)}
            >
              	Light switch
        	</button>
            <div className='light' style={style}>
              	{lightSwitch}
        	</div>
        </div>
    );
};

export default App;

Output:

I created two state variables in this example: ‘lightSwitch‘ and ‘press‘. Then ‘press‘ is added to dependencies in the useEffect hook. So any time when the ‘press‘ changes, the function in useEffect will be called. The function sets the value of the ‘lightSwitch‘ state variable due to the value of ‘press‘.

The special thing is that the hook is called as soon as the component is mounted. As you can see, we run the program and immediately have a message in the console window. If you don’t want this to happen, use useRef.

One more note, if you update the value of a variable via the function inside useEffect and the variable is also present in dependencies, it will cause an endless loop. For instance:

useEffect(() => {
    if (press % 2 === 0) {
      	setlightSwitch('Off');
    } else {
      	setlightSwitch('On');
    }
    console.log('Press the light switch');
    setpress(press + 1);   // This line cause an endless re-render loop
}, [press]);

The function listens for the change of variable ‘press‘, but the value of ‘press‘ is also updated when the function is executed. 

This problem keeps happening over and over, causing an endless re-render loop.

Summary

You finally know how to listen for state changes in React. I hope this method works for you. Thank you for being so interested in the content of the article.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *