Câu hỏi phỏng vấn Reactjs
Câu hỏi

What is state in React?

Câu trả lời

In React, the state refers to an object that represents the parts of the app that can change. Each component can maintain its own state, which holds data or information about the component that can change over time due to user actions, network responses, or other events. When the state object changes, React re-renders the component to reflect the new data.

The state is a powerful feature in React because it allows components to be dynamic and interactive. For example, a state might contain a user's input in a form, a timer's current value, or whether a component is visible or not. The state is private to the component and can only be changed within the component using the setState method in class components or the useState hook in functional components.

In class components, the state is typically initialized in the constructor and can be modified using this.setState(). In functional components, the useState hook is used to introduce state. The useState hook returns a pair: the current state value and a function that allows you to update it.

Here's an example of state in a class component:

javascript Copy
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

And here's an example using the useState hook in a functional compon...

junior

junior

Gợi ý câu hỏi phỏng vấn

middle

How can I make use of Error Boundaries in functional React components?

expert

How to use React.memo() ?

middle

What does shouldComponentUpdate do and why is it important?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào