React JS React Hooks Use Effect

By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates. It is a close replacement for componentDidmount, componentDidUpdate and componentWillUnmount.

We can get more idea by looking below example. you can put this file in /src/components folder and put in /src/App.js file.

1. HookCounter

HookCounter
import React, { useState } from 'react'; function HookCounter() { const [count, setCount] = useState(0); useEffect(() => { console.log('updating document title'); document.title = `you clicked ${count} times`; }) return ( <div> <input type="text" value={name} onChange={e => setName(e.target.value)} /> <button onClick={() => setCount(count + 1)}>Count {count}</button> </div> ) }

In above code, When I click on button, It will show document title as 'you clicked 1 times' and one console log 'updating document title'. Now, I enter 'india' in textbox then it will show same title and console log increased by 5. So, useEffect runs after every render of the component Sometimes it will create a perforce issue. so, we need to call based on condition.

Example
import React, { useState } from 'react'; function HookCounter() { const [count, setCount] = useState(0); useEffect(() => { console.log('updating document title'); document.title = `you clicked ${count} times`; },[count]) return ( <div> <input type="text" value={name} onChange={e => setName(e.target.value)} /> <button onClick={() => setCount(count + 1)}>Count {count}</button> </div> ) }

In above code, useEffect not called when I type in textbox. it is only called when count value is change. So, we can give second parameter to useEffect as dependency.

Below example shows that run effect only once. - It will work as componentDidMount in class component.

Example
import React, { useState } from 'react'; function HookCounter() { const [count, setCount] = useState(0); useEffect(() => { console.log('updating document title'); document.title = `you clicked ${count} times`; },[]) return ( <div> <input type="text" value={name} onChange={e => setName(e.target.value)} /> <button onClick={() => setCount(count + 1)}>Count {count}</button> </div> ) }

In above code, we pass second parameter in useEffect is empty array []. So, it will call useEffect only once.

 

← Previous

Next →