All Projects β†’ kentcdodds β†’ Stop Runaway React Effects

kentcdodds / Stop Runaway React Effects

Licence: mit
πŸƒ Catches situations when a react use(Layout)Effect runs repeatedly in rapid succession

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Stop Runaway React Effects

Vscode Es7 Javascript React Snippets
Extension for Javascript/React snippets with search supporting ES7 and babel features
Stars: ✭ 435 (-24.22%)
Mutual labels:  hooks
React Hook
↩ Strongly typed, concurrent mode-safe React hooks
Stars: ✭ 472 (-17.77%)
Mutual labels:  hooks
React Hooks Cheatsheet
πŸ¦– React hooks cheatsheet with live editable examples
Stars: ✭ 520 (-9.41%)
Mutual labels:  hooks
Beautiful React Hooks
πŸ”₯ A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development πŸ”₯
Stars: ✭ 5,242 (+813.24%)
Mutual labels:  hooks
React Use Gesture
πŸ‘‡Bread n butter utility for component-tied mouse/touch gestures in React and Vanilla Javascript.
Stars: ✭ 5,704 (+893.73%)
Mutual labels:  hooks
Mobx Router
A simple router for MobX + React apps
Stars: ✭ 489 (-14.81%)
Mutual labels:  hooks
Relay Hooks
Use Relay as React hooks
Stars: ✭ 423 (-26.31%)
Mutual labels:  hooks
Husky
Git hooks made easy 🐢 woof!
Stars: ✭ 25,056 (+4265.16%)
Mutual labels:  hooks
Winxp
🏁 Web based Windows XP desktop recreation.
Stars: ✭ 4,717 (+721.78%)
Mutual labels:  hooks
React Hooks
Essential set of React Hooks for convenient Web API consumption and state management.
Stars: ✭ 515 (-10.28%)
Mutual labels:  hooks
React Recipes
πŸ‘©β€πŸ³ A React Hooks utility library containing popular customized hooks
Stars: ✭ 452 (-21.25%)
Mutual labels:  hooks
React Hooks Lib
A set of reusable React Hooks.
Stars: ✭ 460 (-19.86%)
Mutual labels:  hooks
Maily
πŸ“« Rails Engine to preview emails in the browser
Stars: ✭ 502 (-12.54%)
Mutual labels:  hooks
Easy Peasy
Vegetarian friendly state for React
Stars: ✭ 4,525 (+688.33%)
Mutual labels:  hooks
Usedimensions
A React Hook to measure DOM nodes
Stars: ✭ 537 (-6.45%)
Mutual labels:  hooks
Openpbs
An HPC workload manager and job scheduler for desktops, clusters, and clouds.
Stars: ✭ 427 (-25.61%)
Mutual labels:  hooks
Atomico
Atomico a micro-library for creating webcomponents using only functions, hooks and virtual-dom.
Stars: ✭ 481 (-16.2%)
Mutual labels:  hooks
React Fetching Library
Simple and powerful API client for react πŸ‘ Use hooks or FACCs to fetch data in easy way. No dependencies! Just react under the hood.
Stars: ✭ 561 (-2.26%)
Mutual labels:  hooks
Gear
A lightweight, composable and high performance web service framework for Go.
Stars: ✭ 544 (-5.23%)
Mutual labels:  hooks
Animavita
Trigger life-saving alerts, register animals for adoption and find the closest pet friend to adopt 🐢
Stars: ✭ 508 (-11.5%)
Mutual labels:  hooks

stop-runaway-react-effects πŸƒ

Catches situations when a react use(Layout)Effect runs repeatedly in rapid succession


Build Status Code Coverage version downloads MIT License

All Contributors PRs Welcome Code of Conduct

The problem

React's useEffect and useLayoutEffect hooks accept a "dependencies array" argument which indicates to React that you want the callback to be called when those values change between renders. This prevents a LOT of bugs, but it presents a new problem.

If your use(Layout)Effect hook sets state (which it very often does), this will trigger a re-render which could potentially cause the effect to be run again, which can lead to an infinite loop. The end result here is that the effect callback is called repeatedly and that can cause lots of issues depending on what that effect callback does (for example, you could get rate-limited by an API you're hitting).

Yes, I'm aware that it's unfortunate that we have this problem at all with React. No, I don't think that hooks are worse than classes because of this. No, I'm afraid that this probably can't/shouldn't be built-into React because sometimes your effect just runs a lot and that's intentional. But most of the time it's not intentional so this tool is here to help you know when it's happening so you can fix it.

This solution

This is a development-time only tool which will help you avoid running into this issue. It wraps React.useEffect and React.useLayoutEffect to provide tracking of the effect callback to determine whether it's called a certain number of times in a certain amount of time. For example. If your effect callback is called 60 times in one second, then it's possible that we have a "runaway effect".

When a runaway effect is detected, stop-runaway-react-effects will log as much info to the console as it knows about the effect callback and its dependencies (as well as some recommendations of what to do about it) and then throw an error to stop the infinite loop.

Table of Contents

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install --save stop-runaway-react-effects

Usage

// src/bootstrap.js
import {hijackEffects} from 'stop-runaway-react-effects'

if (process.env.NODE_ENV === 'development') {
  hijackEffects()
}

// src/index.js
import './bootstrap'
import React, {useEffect} from 'react'

If you're using a modern bundler (like webpack, parcel, or rollup) with modern production techniques, then that code will all get stripped away in production.

If you'd like to avoid the extra file, an even easier way to do this is to use the hijack utility module:

// src/index.js
import 'stop-runaway-react-effects/hijack'
// This is better because it will ensure that the effects are wrapped before you
// import them (like if you're doing named imports):
import React, {useEffect} from 'react'

API

You can customize the callCount and timeLimit by passing them as options:

// as of this writing, this is the default, but the default could change as
// we fine-tune what's more appropriate for this
hijackEffects({callCount: 60, timeLimit: 1000})

You can also wrap one but not the other React effect hook:

import {hijackEffectHook} from 'stop-runaway-react-effects'

if (process.env.NODE_ENV === 'development') {
  hijackEffectHook('useLayoutEffect', {callCount: 60, timeLimit: 1000})
}

Here are some examples of code and output:

function RunawayNoDeps() {
  const [, forceUpdate] = React.useState()
  React.useEffect(() => {
    // hi, I'm just an innocent React effect callback
    // like the ones you write every day.
    // ... except I'm a runaway!!! πŸƒ
    setTimeout(() => {
      forceUpdate({})
    })
  })
  return null
}

That code will produce this:

no deps

Edit React Codesandbox


function RunawayChangingDeps() {
  const [, forceUpdate] = React.useState()
  const iNeverChange = 'I am primitive!'
  const iChangeAllTheTime = {
    iAmAn: 'object',
    andIAm: 'initialized in render',
    soI: 'need to be memoized',
  }
  React.useEffect(() => {
    // hi, I'm just an innocent React effect callback
    // like the ones you write every day.
    // ... except I'm a runaway!!! πŸƒ
    setTimeout(() => {
      forceUpdate({})
    })
  }, [iNeverChange, iChangeAllTheTime])
  return null
}

That code will produce this:

changing-deps

Edit React Codesandbox

Inspiration

As an instructor I give a lot of react workshop and I know that when people are learning React hooks, this is a huge pitfall for them. I also bump into this issue myself. So one day I decided to do something about it and now it's packaged up here.

Other Solutions

I'm not aware of any, if you are please make a pull request and add it here!

Contributors

Thanks goes to these people (emoji key):

Kent C. Dodds
Kent C. Dodds

πŸ’» πŸ“– πŸš‡ ⚠️
Alex Young
Alex Young

πŸ“– πŸ’»
David O'Trakoun
David O'Trakoun

πŸ“–
Justin Dorfman
Justin Dorfman

πŸ”
Scott Ashton
Scott Ashton

πŸ’»

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].