惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
P
Privacy & Cybersecurity Law Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 热门话题
C
Cybersecurity and Infrastructure Security Agency CISA
S
Security Affairs
Latest news
Latest news
Security Latest
Security Latest
N
News and Events Feed by Topic
Spread Privacy
Spread Privacy
P
Proofpoint News Feed
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
The Exploit Database - CXSecurity.com
The Last Watchdog
The Last Watchdog
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
V
Vulnerabilities – Threatpost
Hacker News - Newest:
Hacker News - Newest: "LLM"
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
The Cloudflare Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
博客园_首页
S
Secure Thoughts
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
AWS News Blog
AWS News Blog
腾讯CDC
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Register - Security
The Register - Security
N
News and Events Feed by Topic
A
Arctic Wolf
MongoDB | Blog
MongoDB | Blog
爱范儿
爱范儿
Project Zero
Project Zero
A
About on SuperTechFans
罗磊的独立博客
云风的 BLOG
云风的 BLOG
Know Your Adversary
Know Your Adversary
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
K
Kaspersky official blog
L
LINUX DO - 最新话题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Fortinet All Blogs

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
A Simple Explanation of React.useEffect()
Dmitri Pavlutin · 2020-10-13 · via Dmitri Pavlutin Blog

I am impressed by the expressiveness of React hooks. You can do so much by writing so little.

But the brevity of hooks comes at a price — they're relatively difficult to understand at the beginning. That's especially true for useEffect() — the hook that manages side-effects in functional React components.

I'll help you understand useEffect() in an accessible way. Let's get started.

Table of Contents

  • 1. Side-effects
  • 2. useEffect() arguments
    • 2.1 Dependencies argument
  • 3. Component lifecycle
    • 3.1 Component did mount
    • 3.2 Component did update
  • 4. Side-effect cleanup
  • 5. useEffect() in practice
    • 5.1 Fetching data
  • 6. Conclusion

1. Side-effects

A functional React component uses props and/or state to calculate the output. If the component makes calculations that don't target the output value, then these calculations are named side-effects.

Examples of side-effects are fetch requests, manipulating DOM directly, using timer functions like setTimeout(), and more.

Component rendering and the side-effect logic are independent. Performing side-effects directly in the body of the component is a mistake, because the body computes the component's output or calls hooks.

How often the component renders isn't something you can control — if React wants to render the component, you cannot stop it.


function Greet({ name }) {

const message = `Hello, ${name}!`; // Calculates output

// Bad!

document.title = `Greetings to ${name}`; // Side-effect!

return <div>{message}</div>; // Calculates output

}


How to decouple rendering from the side-effect? Welcome useEffect() — the hook that runs side-effects independently of rendering.


import { useEffect } from 'react';

function Greet({ name }) {

const message = `Hello, ${name}!`; // Calculates output

useEffect(() => {

// Good!

document.title = `Greetings to ${name}`; // Side-effect!

}, [name]);

return <div>{message}</div>; // Calculates output

}


2. useEffect() arguments

useEffect() hook accepts 2 arguments:


useEffect(callback[, dependencies]);


  • callback is a function that contains the side-effect logic. callback is executed right after the DOM update.
  • dependencies is an optional array of dependencies. useEffect() executes callback only if the dependencies have changed between renderings.

Put your side-effect logic into the callback function, then use the dependencies argument to control when you want the side-effect to run. That's the sole purpose of useEffect().

React useEffect() Hook

For example, in the previous code snippet you saw the useEffect() in action:


useEffect(() => {

document.title = `Greetings to ${name}`;

}, [name]);


The document title update is the side-effect because it doesn't directly calculate the component output. That's why the document title update is placed in a callback and supplied to useEffect().

Also, you don't want the document title update to run every time Greet component renders. You only want it to happen when the name prop changes — that's the reason you supplied name as a dependency to useEffect(callback, [name]).

2.1 Dependencies argument

dependencies argument of useEffect(callback, dependencies) lets you control when the side-effect runs. If dependencies are:

A) Not provided: the side-effect runs after every rendering.


import { useEffect } from 'react';

function MyComponent() {

useEffect(() => {

// Runs after EVERY rendering

});

}


B) An empty array []: the side-effect runs once after the initial rendering.


import { useEffect } from 'react';

function MyComponent() {

useEffect(() => {

// Runs ONCE after initial rendering

}, []);

}


C) Has props or state values [prop1, prop2, ..., state1, state2]: the side-effect runs once after initial rendering and then only when any dependency value changes.


import { useEffect, useState } from 'react';

function MyComponent({ prop }) {

const [state, setState] = useState('');

useEffect(() => {

// Runs ONCE after initial rendering

// and after every rendering ONLY IF `prop` or `state` changes

}, [prop, state]);

}


Let's detail cases B) and C) since they're often used.

3. Component lifecycle

The dependencies argument of the useEffect() lets you catch certain component lifecycle events: when the component has been mounted or a specific prop or state value has changed.

3.1 Component did mount

Use an empty dependencies array to invoke a side-effect once after component mounting:


import { useEffect } from 'react';

function Greet({ name }) {

const message = `Hello, ${name}!`;

useEffect(() => {

// Runs once, after mounting

document.title = 'Greetings page';

}, []);

return <div>{message}</div>;

}


useEffect(..., []) was supplied with an empty array as the dependencies argument. When configured in such a way, the useEffect() executes the callback just once, after initial rendering (mounting).

Even if the component re-renders with different name property, the side-effect runs just once after initial rendering:


// First render

<Greet name="Eric" /> // Side-effect RUNS

// Second render, name prop changes

<Greet name="Stan" /> // Side-effect DOES NOT RUN

// Third render, name prop changes

<Greet name="Butters"/> // Side-effect DOES NOT RUN


Open the demo.

3.2 Component did update

Each time the side-effect uses props or state values, you must indicate these values as dependencies:


import { useEffect } from 'react';

function MyComponent({ prop }) {

const [state, setState] = useState();

useEffect(() => {

// Side-effect uses `prop` and `state`

}, [prop, state]);

return <div>....</div>;

}


useEffect(callback, [prop, state]) invokes the callback once after mounting, and again after committing the changes to the DOM, if and only if any value in the dependencies array [prop, state] has changed.

By using the dependencies argument of useEffect(), you control when the side-effect is called, independently from the rendering cycles of the component. Again, that's the essence of useEffect() hook.

Let's improve the Greet component by using name prop in the document title:


import { useEffect } from 'react';

function Greet({ name }) {

const message = `Hello, ${name}!`;

useEffect(() => {

document.title = `Greetings to ${name}`;

}, [name]);

return <div>{message}</div>;

}


name prop is mentioned in the dependencies argument of useEffect(..., [name]). useEffect() hook runs the side-effect after initial rendering, and on later renderings only if the name value changes.


// First render

<Greet name="Eric" /> // Side-effect RUNS

// Second render, name prop changes

<Greet name="Stan" /> // Side-effect RUNS

// Third render, name prop doesn't change

<Greet name="Stan" /> // Side-effect DOES NOT RUN

// Fourth render, name prop changes

<Greet name="Butters"/> // Side-effect RUNS


Open the demo.

4. Side-effect cleanup

Some side-effects need cleanup: close a socket, clear timers.

If the callback of useEffect(callback, deps) returns a function, then useEffect() considers that function as an effect cleanup:


useEffect(function callback() => {

// Side-effect...

return function cleanup() {

// Side-effect cleanup...

};

}, dependencies);


Cleanup works the following way:

A) After initial rendering, useEffect() invokes the callback with the side-effect. cleanup function is not invoked.

B) On later renderings, before invoking the next side-effect callback, useEffect() invokes the cleanup function from the previous side-effect execution (to clean up everything after the previous side-effect), then invokes the current side-effect.

C) Finally, after unmounting the component, useEffect() invokes the cleanup function from the latest side-effect.

React useEffect() hook cleanup

Let's see an example of when the side-effect cleanup is useful.

The following component <RepeatMessage message="My Message" /> accepts a prop message. Then, every 2 seconds the message prop is logged to the console:


import { useEffect } from 'react';

function RepeatMessage({ message }) {

useEffect(() => {

setInterval(() => {

console.log(message);

}, 2000);

}, [message]);

return <div>I'm logging to console "{message}"</div>;

}


Open the demo.

Open the demo and type some messages. The console logs every 2 seconds the messages typed into the input. However, you need to log only the latest message.

That's the case to clean up the side-effect: cancel the previous timer when starting a new one. Let's return a cleanup function that stops the previous timer before starting a new one:


import { useEffect } from 'react';

function RepeatMessage({ message }) {

useEffect(() => {

const id = setInterval(() => {

console.log(message);

}, 2000);

return () => {

clearInterval(id);

};

}, [message]);

return <div>I'm logging to console "{message}"</div>;

}


Open the demo.

Open the demo and type some messages. You'll see that every 2 seconds only the latest message logs to the console. Which means that all of the previous timers were cleaned up.

5. useEffect() in practice

5.1 Fetching data

useEffect() can perform data fetching side-effect.

The following component FetchEmployees fetches the employees list over the network:


import { useEffect, useState } from 'react';

function FetchEmployees() {

const [employees, setEmployees] = useState([]);

useEffect(() => {

async function fetchEmployees() {

const response = await fetch('/employees');

const fetchedEmployees = await response.json();

setEmployees(fetchedEmployees);

}

fetchEmployees();

}, []);

return (

<div>

{employees.map(name => <div>{name}</div>)}

</div>

);

}


useEffect() starts a fetch request by calling fetchEmployees() async function after the initial rendering.

When the request completes, setEmployees(fetchedEmployees) updates the employees state with the just fetched employees list.

Note that the callback argument of useEffect(callback) cannot be an async function. But you can always define and then invoke an async function inside the callback itself:


function FetchEmployees() {

const [employees, setEmployees] = useState([]);

useEffect(() => { // <--- CANNOT be an async function

async function fetchEmployees() {

// ...

}

fetchEmployees(); // <--- But CAN invoke async functions

}, []);

// ...

}


To run the fetch request depending on a prop or state value, simply indicate the required dependency in the dependencies argument: useEffect(fetchSideEffect, [prop, stateValue]).

6. Conclusion

useEffect(callback, dependencies) is the hook that manages the side-effects in functional components. callback argument is a function where to put the side-effect logic. dependencies is a list of dependencies of your side-effect: being props or state values.

useEffect(callback, dependencies) invokes the callback after initial rendering (mounting), and on later renderings, if any value inside dependencies has changed.

The next step to mastering useEffect() is to understand and avoid the infinite loop pitfall.

Still have questions about useEffect() hook? Write a comment below!