Loading

Quipoin Menu

Learn • Practice • Grow

react / State in React
interview

Q1. What is state in React?
State is an object that holds data that may change over time within a component. It is managed internally by the component and can be updated using setState (in classes) or the useState hook (in functional components). When state changes, the component re-renders to reflect the new data.

Q2. How do you initialize state in a functional component?
Using the useState hook: const [state, setState] = useState(initialValue). The initialValue can be a primitive, object, or array. Example: const [count, setCount] = useState(0). The setState function is used to update the state and trigger re-render.

Q3. How do you update state in a class component?
In class components, you use this.setState() method. It merges the new state with the existing state. Example: this.setState({ count: this.state.count + 1 }). setState can also accept a function for updates based on previous state. It is asynchronous, so multiple calls may be batched.

Q4. What is the difference between state and props?
Props are read-only and passed from parent to child, while state is internal and mutable. Props are used to configure a component, while state manages data that changes over time. Changes in props are triggered by parent re-renders, while state changes are triggered within the component.

Q5. Can you directly modify state?
No, you should never modify state directly (e.g., this.state.count = 5). Always use setState or the state setter function from useState. Direct mutation bypasses React's re-rendering mechanism and can lead to inconsistencies.