DEV Community

Discussion on: Simplify condition rendering in React.js

florianrappl profile image
Florian Rappl

This is wrong. It's true that the elements are still constructed, but nothing is mounted and since React only goes in top-bottom the non-rendering / non-mounted children will never be looked at.

Look at this example.

   const IF = ({ condition, children }) => {
     if (!condition) return null;
     return <React.Fragment>{children}</React.Fragment>;

   const Example = ({name}) => {
    console.log('Render Example', name);
    return <div />;

ReactDOM.render(<div><IF condition={false}><Example name="false - not displayed" /></IF><IF condition={true}><Example name="true - displayed" /></IF></div>, document.querySelector("#app"))
Enter fullscreen mode Exit fullscreen mode

What you'll see in the console is:

"Render Example", "true - displayed"
Enter fullscreen mode Exit fullscreen mode

(Note there is no false - displayed shown.)

So there shouldn't be any such thing as a network request (which anyway shouldn't appear there, because these things are side-effects and, e.g., useEffect would only be called on mounted components anyway).

The only issue with this approach is that you construct more objects (i.e., React elements) than you would otherwise. This becomes only an issue when you have a larger render tree spawning from there.

rmurati profile image
Redžep Murati Author

Exactly 🙂 Thank you for detailed clarification.

Thread Thread
trusktr profile image
Joe Pea

No issue with extra elements in Solid, no matter how big the app gets. Check it out!