skip to Main Content

I’m learning React. I know about recursion in plain JS functions. And recently I’ve found that this concept exists in React too. It’s called recursive rendering. And you need some condition for it to work like in plain function recursion to stop. But I can’t find an explanation of what happens when I write code like this:

function App() {
  return (
    <App>
      ...other JSX here
    </App>
  );
}

The page just loads infinitely until the browser says that page unresponsive. So what’s happening with React component in this case?

2

Answers


  1. A react component is basically a function that returns some content (JSX in this case).
    So the way a function may call its own instance, a react component may also return its own so to speak.
    To put it in another way, JSX is a sytactic sugar for React.createElement() fucntion and stopping a react component from returning its own JSX happens exactly the same way you stop a recursive function (React.createElement() in this case) by using condition for props of the component (JSX syntax) or parameters of the function (createElement() syntax).

    Login or Signup to reply.
  2. Like sayd above: React components are JS functions (nowadays at least), and in the end it all compiles down to JS so it’ll behave like JS.

    Keeping it simple, when you write a component on your returned JSX you’re calling the function that defines that component.
    Therefore, when you return {children}, you’re calling the App function inside itself, hence the loop.

    To ilustrate, what you’re doing is something like this in plain js:

    function App() {
     return (
        App()
     );
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search