useEffect Hook in React App from scratch
Hooks are very useful when you are building a react app and using function components in your app, It provides the facilities to use state and lifecycle features in your function component.
In this article, we learned What are hooks? and how/where/when we can use hooks in our react app? If you haven’t read this article, I strongly recommend you to read this article first to get a better understanding of hooks.
In this article, we will learn the following things:
* What is useEffect hook?
* When we can use useEffect hook?
* How we can implement useEffect hook in our app?
What is useEffect hook?
In the function component, if you want to do any kind of side effect then you can perform by effect hooks. “useEffect” is a type of hook used to encapsulating codes that has any kind of side effect. Like DOM changes, fetching data from APIs, performing any kind of subscription, set the document title.
If you are using the hook, then you are telling to react that this specific component wants to do some task after render. React will ensure that your function will be called after the render/DOM updates. useEffect run after every render, by defaults it runs after the first render and after every update. useEffect is always called inside a component. useEffect is a combination of componentDidMount, componentDidUpdate and componentWillUnmount.
useEffect = componentDidMount + componentDidUpdate + componentWillUnmount
Always call useEffect inside a component:
using useEffect inside the component has access to the state variables and any props right from the effect, It is in the function scope.
Syntax:
import React, { useEffect } from 'react';
useEffect(function);
or
useEffect(function, Array)
- The function passed to useEffect will run after the render called.
- The second argument ( Array ) of values that effects depend on, means if useEffect will be called if that given variable/object/ gets updated.
Let’s use useEffect hook in our app:
Step 1: Create an app “hooks-demo” using below command:
npx create-react-app hooks-demo
After successful completion of above command run command
cd hooks-demo
npm start
Step 2: Make your app is working:
Open the browser and hit URL http://localhost:3000 and should be displayed the below screen as:
Step 3: Now let’s use “useEffect” in our App component:
Goto the src/App.js and delete all codes and write the below code:
import React, { useState, useEffect } from 'react';
import './App.css';function App() { const [orderCount, setCount] = useState({ count:0 });
const changeCount = () => {
setCount({ count:orderCount.count+1 })
}; useEffect(() => {
console.log('useEffect called');
}); return (
<div>
<h1>count:{orderCount.count}</h1>
<button type='button' onClick={changeCount}>Increment</button
</div>
);
}export default App;
Let’s understand the code first:
we are importing “React” and “useState” in the below line:
import React, { useState, useEffect } from 'react';
Creating a function component App:
function App() { }
Creating a state using “useState” hook with default value { count: 0 }:
const [orderCount, setCount] = useState({ count:0 });
Created a click handler for the button to change the state:
const changeCount = () => {
setCount({ count:orderCount.count+1 })
};
Using useEffect hook in our app component:
useEffect(() => {
console.log('useEffect called');
});
Return HTML to render on the web browser:
return (
<div>
<h1>count:{orderCount.count}</h1>
<button type='button' onClick={changeCount}>Increment</button
</div>
);
Export the app:
export default App;
Step 4: Run the app and see the browser:
Run this app using command “npm start” and open the browser with URL “http://localhost:3000”, It should be displayed like this ( App component ):
Here useEffect called when components get loaded.
Now click on the “Increment” button:
Again “useEffect” gets called when any changes happen in our component or render() called. It means useEffect will be called every after render function gets called. See in the browser after multiple clicks.
So you have seen in the above example, “useEffect” gets called every time your change the state, and after DOM updates.
Conclusion:
In this article, you learned the following things:
* What is useEffect hook?
* How to use useEffect hook?
* Implementation of useEffect in the app.
* Use of useState hook in the app ( in the implementation )
If you’re interested in Node.js or JavaScript, then this link will help.
Thanks for reading.