If you have Basic knowledge of React with class-based components and functional components with hooks then you know we can achieve some life cycle methods of class-based components with useEffect() hooks with its dependency array and return function. like the componentDidUpdate method, we can achieve with useeEffect with no dependency array. But do you know there is some difference in the behavior between them to access state in their scope? Let’s see that difference and understand that:
Pre-requisite:
- Basic Knowledge of Javascript
- ReactJs (class-based component & functional component with hooks)
componentDidUpdate: This is a life cycle method that is used only in the class-based components. it will invoke immediately every time when our component updates.
Syntax:
componentDidUpdate(prevProps, prevState, snapshot)
Setting up Application: Follow the below steps to set up the application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: The project structure should look like below:
Example: To demonstrate the working of componentDidUpdate(). Write down the following code in the App.js file:
Javascript
import { Component } from "react" ; // Create App as class based component so we can // use componentDidUpdate lifeCycle Method class App extends Component { constructor() { super (); this .state = { count: 0 }; } componentDidUpdate() { // We will log count in console after every // update with 500 ms waiting period setTimeout(() => { console.log( this .state.count) }, 500) } render() { return ( <> <h1>Count { this .state.count}</h1> <button onClick={() => this .setState((state) => { return { count: state.count + 1 } })}> Increment </button> </> ); } } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
In the above example, we have used the componentDidUpdate method to print the updated count after every update (after every button click which updates the count by 1)
If you are clicking on the “Increment” button 4 time continuously without any break, On the screen you can see “Count 4” but in the console, you can see 4 is logging 4 times instead of print 1,2,3,4.
Explanation: So when our Component updates that time our componentDidUpdate() method will invoke and register that setTimeout function/callback in the queue. here we have a 500 ms timeout/ waiting time so when this callback executes that time this.state.count refers to the latest value which is 4 in our Case and we have clicked 4 times so in the console we are getting 4 for 4 times.
useEffectHook: It is a React Hook that we can use in functional components. It will execute the callback after any dependency array value will update/change. If we are not passing the dependency array in useEffectHook then it will execute a callback on every update of our component.
Syntax:
useEffect(cb,[]):
Example: To demonstrate the working of useEffectHook. Write down the following code in the App.js file.
Javascript
import { useEffect, useState } from "react" ; const App = () => { // useState for using state in functional Component const [count, setCount] = useState(0); // useEffect with no dependency Array so it // will triggered on every update of this component useEffect(() => { // print count in the console after every // update with 500 ms waiting time setTimeout(() => { console.log(count); }, 500); }); return ( <> <h1>Count {count}</h1> <button onClick={() => setCount((prevCount) => prevCount + 1)}> Increment </button> </> ); }; export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
In the above example, we are doing the same thing which we have done in the previous Class Based component. We are printing count after every updation but this time we are using useEffectHook as we are implementing the functional component.
if we do the same thing like click 4 times on the “Increment” button, this time we are getting 1 2 3 4. why ??
Explanation: So when the count state is updated, useEffect will invoke and register their callback in the queue but this time that callback does not refer latest count state because in useEffecthook callback has stated in its own scope so when the event loop executes these callback that time code will print 1 2 3 4.