React
/Beginner
State (useState)
Definition
The `useState` hook allows you to add state to functional components. State is data that changes over time, and when state changes, React automatically re-renders the component to reflect the new data on the screen.
Explain Like I'm New
Imagine a digital scoreboard at a basketball game. The 'score' is the State. When a team scores, you update the state. React acts as the scoreboard operator—the moment you tell React the new score, it instantly updates the giant screen so the audience can see it. Without State, variables might change in the background, but the screen would never update.
Real World Example
A simple 'Like' button. When the user clicks it, you update `likes + 1`. React notices the change and re-draws the button with the new number.
Common Use Cases
- •Tracking user input in text fields
- •Toggling UI states (e.g., isModalOpen)
- •Storing fetched data from an API to display on screen
Interactive Example
import React, { useState } from 'react'; export default function Counter() { // count is the current state // setCount is the function to update it // 0 is the initial value const [count, setCount] = useState(0); const handleIncrement = () => { // BAD: Might use stale state if called rapidly // setCount(count + 1); // GOOD: Using functional update to guarantee latest state setCount(prevCount => prevCount + 1); }; return ( <div className="counter-box"> <h2>Current Count: {count}</h2> <button onClick={handleIncrement}> Increment </button> <button onClick={() => setCount(0)}> Reset </button> </div> ); }
Interview Questions
basic
- What does `useState` return?
- Why can't you just use a regular let variable instead of useState?
intermediate
- Is `setState` synchronous or asynchronous?
- Why should you use the functional update form (prev => prev + 1) when updating state based on the previous state?
advanced
- What happens if you initialize useState with a heavy computation function: `useState(heavyComputation())` vs `useState(() => heavyComputation())`?
- How does React know which useState call belongs to which variable across re-renders?
trick
- If you call `setState(5)` three times in a row, how many times does the component re-render?