To make a component have state, you should...

Master ReactJS with our comprehensive test. Practice with multiple-choice questions and detailed explanations. Build your skills for the exam with our engaging format and expert tips!

Multiple Choice

To make a component have state, you should...

Explanation:
In a class-based React component, state is stored on the instance as this.state, and you initialize it inside the constructor by assigning this.state to an object. This runs when the component is created, so the initial values are available for the first render. For example, inside the constructor you’d do something like this.state = { count: 0 };. After that, you should update state with this.setState rather than mutating this.state directly, which lets React know to re-render. The other options don’t fit the common pattern for establishing initial state in a class component. Using a functional component involves hooks to manage state, not this.state on a class. Declaring a state property outside the constructor resembles newer class-field syntax, but the traditional and most explicit approach shown here is to initialize state inside the constructor. Using getDerivedStateFromProps is a lifecycle method meant for deriving state from props, not for setting the initial state.

In a class-based React component, state is stored on the instance as this.state, and you initialize it inside the constructor by assigning this.state to an object. This runs when the component is created, so the initial values are available for the first render. For example, inside the constructor you’d do something like this.state = { count: 0 };. After that, you should update state with this.setState rather than mutating this.state directly, which lets React know to re-render.

The other options don’t fit the common pattern for establishing initial state in a class component. Using a functional component involves hooks to manage state, not this.state on a class. Declaring a state property outside the constructor resembles newer class-field syntax, but the traditional and most explicit approach shown here is to initialize state inside the constructor. Using getDerivedStateFromProps is a lifecycle method meant for deriving state from props, not for setting the initial state.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy