React - Pass State as Props to Child Components

Tell us what’s happening:
Hello, I keep solving challenges on react and repeatedly see the pattern: a class is referred before it is declared. Like in the challenge below: first we reference Navbar in the MyApp class and then we declare the Navbar class. Can anyone explain please why it works? Thank you.
Your code so far

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'CamperBot'
    }
  }
  render() {
    return (
       <div>
         {/* Change code below this line */}
         <Navbar />
         {/* Change code above this line */}
       </div>
    );
  }
};

class Navbar extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
    <div>
      {/* Change code below this line */}
      <h1>Hello, my name is: </h1>
      {/* Change code above this line */}
    </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

Challenge: React - Pass State as Props to Child Components

Link to the challenge:

I don’t really know the internals of how the classes are used by React but I’m guessing it is much for the same reason as why you can do this.

const useFn = () => {
  console.log(fnToUse()); // Hello World
};

const fnToUse = () => {
  return 'Hello World';
};

useFn();

It might look like fnToUse is used before its declaration but it isn’t.

1 Like

Thank you very much. I think you are right and probably something similar is happening behind the scenes.

Just to add to this.

Classes are not hoisted, just like functions declared using const/let are not hoisted.

So you can’t do this…

const sayName = new Name('John'); // Cannot access 'Name' before initialization
sayName.sayName();

class Name {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    console.log(this.name);
  }
}

Or this…

useFn(); // Cannot access 'useFn' before initialization

const useFn = () => {
  console.log(fnToUse());
};

const fnToUse = () => {
  return 'Hello World';
};

But you can do this…

useFn();

function useFn () {
  console.log(fnToUse()); // Hello World
};

function fnToUse() {
  return 'Hello World';
};

Thanks a lot, very interesting! Will read about hoisting now.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.