When exactly is state available in React?

78 views Asked by At

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

There are 2 answers

2
Nja On

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);
} 
0
DangerousDetlef On

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.