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

推荐订阅源

U
Unit 42
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News | PayPal Newsroom
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
S
Security @ Cisco Blogs
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
Help Net Security
Help Net Security
Latest news
Latest news
NISL@THU
NISL@THU
S
Security Affairs
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
小众软件
小众软件
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
AWS News Blog
AWS News Blog
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
I
InfoQ
Schneier on Security
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
IT之家
IT之家
T
Threatpost
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
S
SegmentFault 最新的问题

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 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 React.useEffect() 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
How to Solve the Infinite Loop of React.useEffect()
Dmitri Pavlutin · 2021-01-19 · via Dmitri Pavlutin Blog

useEffect() hook manages the side-effects like fetching over the network, manipulating DOM directly, and starting/ending timers.

Although the useEffect() is one of the most used hooks along with useState(), it requires time to familiarize and use correctly.

A pitfall you might experience when working with useEffect() is the infinite loop of component renderings. In this post, I'll describe the common scenarios that generate infinite loops and how to avoid them.

1. The infinite loop and side-effect updating state

Let's say you want to create a component having an input field, and also display how many times the user changed that input.

Here's a possible implementation of <CountInputChanges> component:


import { useEffect, useState } from 'react';

function CountInputChanges() {

const [value, setValue] = useState('');

const [count, setCount] = useState(-1);

useEffect(() => setCount(count + 1));

const onChange = ({ target }) => setValue(target.value);

return (

<div>

<input type="text" value={value} onChange={onChange} />

<div>Number of changes: {count}</div>

</div>

)

}


<input type="text" value={value} onChange={onChange} /> is a controlled component.

value state variable holds the input value, and the onChange event handler updates the value state when the user types into the input.

I decided to update the count variable using useEffect() hook. Every time the component re-renders due to the user typing into the input, the useEffect(() => setCount(count + 1)) updates the counter.

Because useEffect(() => setCount(count + 1)) is used without the dependencies argument, () => setCount(count + 1) callback is executed after every rendering of the component.

Do you expect any problems with this component? Open the demo.

The demo shows that count state variable increases uncontrollably, even if you haven't typed anything into the input. That's an infinite loop.

The problem is in the way useEffect() is used:


useEffect(() => setCount(count + 1));


which generates an infinite loop of component re-renderings.

After initial rendering, useEffect() executes the side-effect callback and updates the state. The state update triggers re-rendering. After re-rendering useEffect() executes the side-effect callback and again updates the state, which triggers again a re-rendering. ...and so on indefinitely.

React useEffect() infinite loop

1.1 Fixing dependencies

The infinite loop is fixed with correct management of the useEffect(callback, dependencies) dependencies argument.

Because you want count to increment when value changes, you can simply add value as a dependency of the side-effect:


import { useEffect, useState } from 'react';

function CountInputChanges() {

const [value, setValue] = useState('');

const [count, setCount] = useState(-1);

useEffect(() => setCount(count + 1), [value]);

const onChange = ({ target }) => setValue(target.value);

return (

<div>

<input type="text" value={value} onChange={onChange} />

<div>Number of changes: {count}</div>

</div>

);

}


By adding [value] as a dependency of useEffect(..., [value]), the count state variable will only be updated when [value] changes. This solves the infinite loop.

React useEffect() controlled rendering loop

Open the fixed demo. Now, as soon as you type into the input field, the count state correctly displays the number of input value changes.

1.2 Using a reference

An alternative solution is to use a reference (created by useRef() hook) to store the number of changes of the input.

The idea is that updating a reference doesn't trigger re-rendering of the component.

Here's a possible implementation:


import { useState, useRef } from 'react';

function CountInputChanges() {

const [value, setValue] = useState('');

const countRef = useRef(0);

const onChange = ({ target }) => {

setValue(target.value);

countRef.current++;

};

return (

<div>

<input type="text" value={value} onChange={onChange} />

<div>Number of changes: {countRef.current}</div>

</div>

);

}


Inside the event handler onChange the countRef.current++ is executed each time the value state changes. The reference change doesn't trigger re-rendering.

Check out the demo. Now, as soon as you type into the input field, the countRef reference is updated without triggering a re-rendering — efficiently solving the infinite loop problem.

2. The infinite loop and new objects references

Even if you set up correctly the useEffect() dependencies, still, you have to be careful when using objects as dependencies.

For example, the following CountSecrets component monitors the words that the user types into the input, and as soon as the user types the special word 'secret', a counter of secrets is increased and displayed.

Here's a possible implementation of the component:


import { useEffect, useState } from "react";

function CountSecrets() {

const [secret, setSecret] = useState({ value: "", countSecrets: 0 });

useEffect(() => {

if (secret.value === 'secret') {

setSecret(s => ({...s, countSecrets: s.countSecrets + 1}));

}

}, [secret]);

const onChange = ({ target }) => {

setSecret(s => ({ ...s, value: target.value }));

};

return (

<div>

<input type="text" value={secret.value} onChange={onChange} />

<div>Number of secrets: {secret.countSecrets}</div>

</div>

);

}


Open the demo and type some words, one of which should be 'secret'. As soon as you type the word 'secret', the secret.countSecrets state variable starts to grow uncontrollably.

That's an infinite loop problem.

Why is this happening?

The secret object is used as a dependency of useEffect(..., [secret]). Inside the side-effect callback, as soon as the input value equals 'secret', the state updater function is called:


setSecret(s => ({...s, countSecrets: s.countSecrets + 1}));


which increments the secrets counter countSecrets, but also creates a new object.

secret now is a new object and the dependency has changed. So useEffect(..., [secret]) invokes again the side-effect that updates the state and a new secret object is created again, and so on.

2 objects in JavaScript are equal only if they reference exactly the same object.

2.1 Avoid objects as dependencies

Because of the objects creation and referential equality problem, it's wise to avoid objects as deps in useEffect(). Stick to primitives when possible:


let count = 0;

useEffect(() => {

// some logic

}, [count]); // Good!



let myObject = {

prop: 'Value'

};

useEffect(() => {

// some logic

}, [myObject]); // Not good!

useEffect(() => {

// some logic

}, [myObject.prop]); // Good!


Fixing the infinite loop of <CountSecrets> component requires changing the dependency from useEffect(..., [secret]) to useEffect(..., [secret.value]).

Calling the side-effect callback when only secret.value changes is sufficient. Here's the fixed version of the component:


import { useEffect, useState } from "react";

function CountSecrets() {

const [secret, setSecret] = useState({ value: "", countSecrets: 0 });

useEffect(() => {

if (secret.value === 'secret') {

setSecret(s => ({...s, countSecrets: s.countSecrets + 1}));

}

}, [secret.value]);

const onChange = ({ target }) => {

setSecret(s => ({ ...s, value: target.value }));

};

return (

<div>

<input type="text" value={secret.value} onChange={onChange} />

<div>Number of secrets: {secret.countSecrets}</div>

</div>

);

}


Open the fixed demo. Type some words into the input... and as soon as you enter the special word 'secret' the secrets counter increments. No infinite loop is created. That's a win!

3. Summary

useEffect(callback, deps) is the hook that executes callback (the side-effect) after deps changes. If you aren't careful with what the side-effect does, you might trigger an infinite loop of component renderings.

A common case that generates an infinite loop is updating the state in the side-effect without having any dependency argument at all:


useEffect(() => {

// Infinite loop!

setState(count + 1);

});


An efficient way to avoid the infinite loop is to properly manage the hook dependencies — control when exactly the side-effect should run.


useEffect(() => {

// No infinite loop

setState(count + 1);

}, [whenToUpdateValue]);


Alternatively, you can also use a reference. Updating a reference doesn't trigger a re-rendering:

Another common recipe for an infinite loop is to use an object as a dependency of useEffect(), and within the side-effect, update that object (effectively creating a new object):


useEffect(() => {

// Infinite loop!

setObject({

...object,

prop: 'newValue'

})

}, [object]);


Avoid using objects as dependencies, but use the object property values directly as dependencies:


useEffect(() => {

// No infinite loop

setObject({

...object,

prop: 'newValue'

})

}, [object.whenToUpdateProp]);


I recommend checking also my post 5 Mistakes to Avoid When Using React Hooks.

What other infinite loop pitfalls when using useEffect() do you know?