Which is a correct way to create a state in a class component?
class MyComponent extends React.Component { ... }

Working with State in a React Class Component

When building applications with React.js, one of the essential concepts is managing the state of the component. The state is an object that stores the component's local or private data, which may not be accessible to other components.

So, how do we create a state in a class component? The answer is: this.state = { value: '' };.

Upon creation of a class component in React, you can define an initial state of the component. This is usually done within the constructor of the class. It sets up the component with necessary initialization, such as setting the initial state and binding methods to this.

Here is an example:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };
  }

  render() {
    return <div>{this.state.value}</div>;
  }
}

In this example, we set the initial state of the component MyComponent to { value: '' }. Each time you want to change (update) the state, you use the method this.setState() - a built-in React method. This ensures that React is aware of the state change and will re-render the component to reflect this.

setNewValue() {
  this.setState({ value: 'Hello, world!' });
}

It's important to note that this.state should be considered as read-only. One should change the state via this.setState() - as demonstrated above. The other provided options, such as const state = { value: '' };, useState({ value: '' });, or setState({ value: '' });, are incorrect ways to define state in a React class component.

  • const state = { value: '' }; is not specific to the component. This is the standard JavaScript way of declaring a variable but does not refer to the component state.
  • useState({ value: '' }); is a Hook that lets you add React state to functional components, but not class components.
  • setState({ value: '' }); is used to update the state, not to define it.

By understanding how to correctly create a state in a class component, you're on the right path to create dynamic and interactive UIs with React.

Do you find this helpful?