React: Provide a way to detect infinite component rendering recursion in development

Created on 3 Apr 2018  Â·  14Comments  Â·  Source: facebook/react

Do you want to request a feature or report a bug?

  • Feature (possibly bug?)

What is the current behavior?

I've been trying out the new Context API in my project and it's awesome. However, in my haste to start using it, I managed to stumble into a situation where every time I would try and render a certain component which was making use of a few different contexts, the app would completely freeze, and the only thing that would let me get out of this error state was to forcefully kill the process via the chrome task manager.

Nothing would be logged to the console, the app would just completely freeze, and when I opened up the task manager and saw the CPU spiked up every time i would go to this component, and the only way I could stop it was to crash the tab.

I finally threw some console statements in and saw that it had just entered into an infinite loop between these providers. I managed to get the app to stop crashing, but I'm still unsure as to why exactly this was happening. I'm sure I was just using this API incorrectly somehow, but this was a very confusing problem to diagnose, and some error checking here would be incredibly useful

What is the expected behavior?

It would be very beneficial to have some sort of checks in place, similar to what happens with too many setState calls happening too closely when you call it from componentDidUpdate, for example. That way, instead of freezing everything up permanently, the app could at least crash and report some sort of information and help me realize where I'd gone wrong.

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

  • React 16.3.0
  • Chrome 65.0.3325.181
Stale Feature Request

Most helpful comment

Honestly I think it really is effictively just a more roundabout form of your second example. It's easy to see when it's like that, but it gets more difficult to diagnose when you have used 3 or 4 HOCs on top of otherwise unrelated components that then happen to call each other.

I guess what I'm requesting here is really just some sort of measure to detect this and throw an error, and break out of that loop somehow, so recursive issues such as this can be diagnosed easier, much like how you handle too many setState calls occurring too close together.

All 14 comments

Is there something specific to context here? I guess you'd have a similar problem if you rendered a component that recursively renders itself?

@gaearon Is it the same issue I post it before two days? here?
https://github.com/facebook/react/issues/12515

Yeah that's basically what was going on, it was just a recursive call with no end condition, and I just didn't realize as I was writing it.

It's probably more that I was using HOC functions to do this, and those functions were recursively calling each other without me realizing.

I had set up a few different functions like this to combine common contexts:

const AppContextTypeContext = React.createContext('None');
const AppContextIdContext = React.createContext(0);

function AppContextProvider({ contextType, contextId, ...props }) {
    return (
        <AppContextTypeContext.Provider value={contextType}>
            <AppContextIdContext.Provider value={contextId} {...props} />
        </AppContextTypeContext.Provider>
    );  
}

with matching HOC functions for the context like this:

const withAppContext = WrappedComponent => function WithAppContext(props) {
    return (
        <AppContextTypeContext.Consumer>
            {contextType => (
                <AppContextIdContext.Consumer>
                    {contextId => <WrappedComponent contextType={contextType} contextId={contextId} {...props} />}
                </AppContextIdContext.Consumer>
            )}
        </AppContextTypeContext.Consumer>);
};

and I was combining them in multiple ways in multiple spots, and I guess I just ended up with the wrong combination of these functions that led to this issue.

So in short yeah, it's probably not specific just to contexts, but I could see many others easily running into this issue like I did.

This does seem to be a duplicate of #12515, though it's been a helpful discussion so far.

I'm just struggling to see how #12515 or this is different from just

function Child() {
  return <Child />;
}

or

function A() {
  return <B />;
}

function B() {
  return <A />;
}

Honestly I think it really is effictively just a more roundabout form of your second example. It's easy to see when it's like that, but it gets more difficult to diagnose when you have used 3 or 4 HOCs on top of otherwise unrelated components that then happen to call each other.

I guess what I'm requesting here is really just some sort of measure to detect this and throw an error, and break out of that loop somehow, so recursive issues such as this can be diagnosed easier, much like how you handle too many setState calls occurring too close together.

I think the issue is technically unrelated to context, though it seems to be easier to run into with the new context API. Is there any built in safeguard to prevent too much recursion or would a check for this be easy to add at least for debugging purposes?

What would be the desired solution here; keep track of how deep components have nested during rendering and abort with message when it's too deep? (200? 500?)

I was originally thinking about warning when a component's child renders another instance of itself, but that could have confusing false positives. I guess setting a max depth is a good compromise, if it only warns in dev.

It’s not necessarily what you’re looking for, but I find the npm package “why did you update” to be useful in identifying unnecessary rerenders.

This is basically the halting problem, a program cannot be created that will determine if another program will ever stop running. However, you can set some form of counter and after so many iterations halt a program.

I don't think it is a something that should be added as it's the same idea across all programming languages, if you keep calling a function infinitely, your program will run infinitely.

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contribution.

Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!

//Custom hook_1
const useRenderCount = () => {
  // src: https://medium.com/better-programming/how-to-properly-use-the-react-useref-hook-in-concurrent-mode-38c54543857b
  const renderCount = useRef(0);
  let renderCountLocal = renderCount.current;
  useEffect(() => {
    renderCount.current = renderCountLocal;
  });
  renderCountLocal++;
  return renderCount.current;
};

//Custom hook_2 (We just need this, we'll call the other one implicitly).
const useStopInfiniteRender = (maxRenders) => {
  const renderCount = useRenderCount();
  if (renderCount > maxRenders)  throw new Error('Infinite Renders limit reached!!');
};

And using that custom hook in a react component like,

  const App () => {

  useStopInfiniteRender(10); //This works great for me, but it'll throw error at 11th render. 
  // You may set it to your need like 10000 is a good number.

  //...more code..
  }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jimfb picture jimfb  Â·  3Comments

framerate picture framerate  Â·  3Comments

hnordt picture hnordt  Â·  3Comments

trusktr picture trusktr  Â·  3Comments

krave1986 picture krave1986  Â·  3Comments