Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

What is State in React and How to Use It?

In React, state is a built-in object that allows components to create and manage their own data — essentially a way to store information that can change over time. When the state of a component changes, React automatically re-renders the component to reflect the new state on the screen.

Think of state as "data that can change" in your app, and whenever it changes, React updates the UI for you.

How to Use State

In class components, state is usually initialized in the constructor and updated using this.setState():

class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } }

In function components (which are more common now), we use the useState hook:

import React, { useState } from 'react'; function Example() { const [count, setCount] = useState(0); const increment = () => { setCount(count + 1); }; return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); }

Key Points About State:

  • State is local to a component and cannot be accessed by other components unless passed as props.
  • Changing state should always be done using setState (in classes) or the updater function (like setCount) (in hooks), never by modifying the state variable directly.
  • State updates are asynchronous — React may batch multiple state updates together for performance reasons.