0

I was interviewed for a front end developer position the other day and was asked this question verbatim. He noted it was a "gotcha" question. I was not sure what the actual answer is. Would it be something like componentDidMount from a lifecycle method perspective?

Thank you for the responses!

2 Answers2

0

The state of the component is declared and initialized in the constructor, the first component method called by react.

  constructor(props) {
    super(props);    
    this.state = {date: new Date()};
  }

In this image you can see all the stage of a react component lifecycle:

react lifecycle

It would be available before the component did mount as componentDidMount method is called once its get rendered

In case of functional components state will be available during the render phase as it is initialized by the hook useState

function myComponent(props) {
    const [stateVar, setStateVar] = useState(0);
} 
Nja
  • 439
  • 6
  • 17
  • An interesting thing to note is that it's now abstracted away a bit because of [Class instance fields](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields). Which allows us to not have to use the constructor at all. -- And for function components, the state becomes available at the point the `useState` hook was called in the render. – Zachary Haber Oct 12 '20 at 14:51
  • Tthank for the carification @Zachary i wasn't considering functional components! – Nja Oct 12 '20 at 14:56
0

I think you answer is right, kind of. The more general response would probably be that the state of a component is available when it has been mounted.

At the core of ReactJS, there is the virtual DOM, which manages states and props and updates your real DOM when changes in these props and states in the virtual DOM occur. So another probably correct answer would be that the state is available as soon as it's loaded in the virtual DOM - and that happens when the component is mounted.

Edit: Adding to add since the other answer saw a different approach: Yes, you can set the state in constructor and you could count that as "available", however it's no use to you since your component isn't mounted at this point. You can even change it in the constructor, but it has no use - there is no mounted component that could use this change. It also can't be used by any child component as long as the parent component is not rendered.

There may be some edge cases I'm not seeing here, but generally I'd say "available" means when I can use it, manipulate it and show the changes of the state - which happens when the component mounted.

Certainly this depends on the point of view your interviewer is asking this from, but if you argue it that way, I'd say it's a correct answer.

DangerousDetlef
  • 371
  • 2
  • 11