Search code examples
javascriptreactjsuse-effect

Too many re-renders with useState and useEffect


I've been having a problem with my code where it goes into an infinite re-render loop with my getComponent function. I'm pretty sure the problem is with me using setComponent, and it rendering each time it's called. I tried using useCallback but that didn't work. The intent behind this code is to loop through an array, rendering certain components and passing props based on entries inside it. I'm new to React, so I'm sure there's a simple solution to this I can't find. In any case, I would appreciate help on this, or other parts of the code if you think it can be improved.

Thanks!

Codesandbox - There is question array that axios call is supposed to fetch at bottom.


Solution

  • There is no need to have a state 'component'. You should ideally return a component from your switch statement. Here's the modified codesandbox.

    Notice that -

    • I have removed 'component' and 'setComponent'
    • Returned the relevant component in switch statement
    • Cleaned up the map function used inside the return statement.