Skip to main content

Command Palette

Search for a command to run...

5) States in React

Updated
  1. Concept of useState
    useState is a React hook that lets you add state variables to functional components.
    When you call it, it returns two values:
    The current state value and A function to update that state.

    const [state, setState] = useState(initialValue);
    

    i) state → the current value
    ii) setState → function used to update the value
    iii) initialValue → starting value (number, string, array, object, boolean, etc.)

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

    i) When the component renders, React reads the useState initial value.
    ii) When you call setState, React updates the state and re-renders the component using the new state value.

  2. How useState hook works in React?
    The useState hook works by enabling React to remember state values across re-renders of a functional component. Even though the component function runs again during each re-render, React keeps a persistent internal memory of state values.
    i) React Stores State Internally (Not Inside the Component Function)
    React does not store count inside your function. Instead, React uses an internal list (a "hook state array") to store: The current state value and The setter function.
    ii) First Render: Initial Value Is Used
    On the first render, React calls your component function. It encounters useState(0) and It stores 0 as the initial state.
    It returns: count = 0 and setCount (a function that can update the state)
    iii) Updating the State Triggers a Re-render
    When you set setCount(count + 1);
    React performs the following -
    Stores the new state value, Marks the component to re-render, Calls your component function again, Provides the updated state during re-render.
    So the second time the component runs - It sees useState(0) in the code, But React does not use 0 again Instead, it reads the state value stored earlier.
    4) State Persists Across Renders
    The state variable prints updated values each render because React retrieves state from its internal memory, not from the function.
    5) setState Is Asynchronous and Batched
    React batches multiple updates to improve performance.

    setCount(count + 1);
    setCount(count + 1);
    

    You may not get 2 increments because React batches updates. To fix this, use functional updates,

    setCount(prev => prev + 1);
    setCount(prev => prev + 1);
    
  3. When to use useState hook in React?
    i) When to Use useState in React
    ii) When state updates are straightforward - If updating the state does not require complex logic, useState is perfect.
    iii) When the state is local to one component
    If the state does NOT need to be accessed outside the component, useState is ideal.
    iv) For immediate UI updates
    If you want to update UI directly based on user actions: Button clicks, Typing in inputs, Selecting a drop-down.
    v) When each piece of state is independent
    If the component contains multiple states but they don’t depend on each other.

  4. Beginner-Level Questions
    i) What is the useState hook in React?
    ii) Why do we use useState?
    iii) What is the syntax of useState?
    iv) What does useState return?
    v) Can we pass any data type as the initial value to useState?
    vi) What is the purpose of the setter function returned by useState?
    vii) Does calling setState replace or merge the state?
    viii) What happens when you directly modify the state without using the setter function?
    ix) Why is initial state passed only during the first render?
    x) Can you use useState inside loops, if conditions, or nested functions? Why not?

  5. Intermediate-Level Questions
    i) How does React preserve state between re-renders?
    ii) Are state updates synchronous or asynchronous in React?
    iii) Why does updating state not immediately reflect in logs?
    iv) How do you update an object or array using useState?
    v) What is the functional update form of setState and when should you use it?vi) What will happen if you call the setter function multiple times in the same render?
    vii) What is state batching in React?
    viii) How do you reset state back to the initial value?
    ix) What is the difference between useState and class component setState?
    x) What happens if you pass a function into useState as the initial value? (Lazy initialization)

  6. Advanced-Level Questions
    i) Explain lazy initialization in useState with an example.
    ii) Why does React re-render a component when state changes?
    iii) How does React compare old and new state values to decide re-rendering?iv) Why is updating nested state challenging with useState?
    v) When should you choose useReducer over useState?
    vi) What are the limitations of useState?
    vii) Can you optimize re-renders when using useState? How? (with React.memo, etc.)
    viii) How would you manage a large or deeply nested state with useState?
    ix) Why must useState be called in the same order on every render?
    x) Can you store functions in state? What’s the use case?

  7. Practical Coding Questions
    i) How do you toggle a boolean state using useState?
    ii) How do you update a specific item in an array stored in useState?
    iii) How do you manage multiple form inputs using useState?
    iv) What happens when you update state inside an event handler versus inside an effect?
    v) Implement a counter component using useState with increment, decrement, and reset.

  8. Tricky Interview Questions
    i) Why does setState inside a loop behave differently than expected?
    ii) What happens if you call setState using the old value vs using a functional update?
    iii) Why does updating state inside a useEffect cause an infinite loop?
    iv) Does useState update synchronously inside setTimeout? Why?
    v) Why does React sometimes skip re-renders when updating state?