Controlling side effects in useEffect
1. To run useEffect on every render do not pass any dependency
useEffect(()->{
// Example Code
})
2. To run useEffect only once on the first render pass any empty array in the dependecy
useEffect(()->{
// Example Code
}, [] )
3. To run useEffect on change of a particular value. Pass the state and props in the dependency array
useEffect(()->{
// Example Code
}, [props, state] )
React UseEffect Hook Example:
Let’s look at an example of how to use the useEffect hook as a feature that can mimic the life-cycle methods but in functional components. The functional component will look like the code below:
Example: This example demonstrates the use of useEffect Hooks to render the click counts.
Javascript
// File name - HookCounterOne.js // useEffect is defined here import { useState, useEffect } from "react" ; function HookCounterOne() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); return ( <div> <button onClick={() => setCount((prevCount) => prevCount + 1)}> Click {count} times{ " " } </button> </div> ); } export default HookCounterOne; |
Javascript
// Filename - App.js // Importing and using HookCounterOne import React from "react" ; import "./App.css" ; import HookCounterOne from "./components/HookCounterOne" ; function App() { return ( <div className= "App" > <HookCounterOne /> </div> ); } export default App; |
Output: Initially, the document title reads “You clicked 0 times”. when you click on the button, the count value increments, and the document title is updated.
useEffect
triggers a function on every component render, leveraging React to execute specified tasks efficiently.- Positioned within the component, it grants easy access to state and props without additional coding.
- For replicating lifecycle methods in functional components, copy and customize the provided code snippet according to your needs.
ReactJS useEffect Hook
React useEffect hook handles the effects of the dependency array. The useEffect
Hook allows us to perform side effects on the components. fetching data, directly updating the DOM and timers are some side effects. It is called every time any state if the dependency array is modified or updated.
Table of Content
- What is useEffect hook in React?
- Why choose useEffect hook?
- How does it work?
- Importing useEffect hook
- Structure of useEffect hook
- Controlling side effects in useEffect
- Ways to mimic lifecycle methods using useEffect hook