Home > Back-end >  Why is function not called when virtually-rendered only
Why is function not called when virtually-rendered only

Time:06-05

I am trying to understand when the function body of the Label function I have here will run.

export default function App() {
  const label = <Label>Foo</Label>;

  return <Button>{label}</Button>;
}

const Button = (props) => {
  const shouldRenderChildren = false;

  return <button>{shouldRenderChildren && props.children}</button>;
};

const Label = () => {
  console.log("runing Label function");
  return <span>label</span>;
};

I created a Codesandbox - enter image description here

Therefore, I believe that at the very most, this line

const label = <Label>Foo</Label>;

is just calling the constructor for the component. This is what the docs says about the constructor:

The constructor for a React component is called before it is mounted

If you want to test it, the convert your component to a class component, and add some console.log to the constructor, then see what happens when you do: const label = <Label>Foo</Label>;

EDIT

I tested it, and not even the constructor of the component is invoked when it is not mounted:

https://codesandbox.io/s/why-is-label-render-not-called-vt05we

Therefore, it might best to assume that until a component is about to be rendered, it is not even constructed!

  • Related