A react interview question on counter | Chai aur react tutorial #8 Summary

Vishesh GuptaVishesh Gupta
2 min read

In this video Watch - Chai aur react #8, the focus was on a common React interview question involving a counter. Here’s what I learned:

  1. Basic Counter Setup:

    • We created a simple counter component to understand how it works.
  2. Interview Scenario:

    • The interviewer might ask, “If we call the function to increment the counter multiple times quickly, how will it behave?”

    • For example, if we increment the counter five times in a row, will the counter value increase by five or just once?

  3. Batch Updates with Fiber and Virtual DOM:

    • React uses the Fiber architecture and Virtual DOM to optimize updates. When you call the state update function multiple times in quick succession, React batches these updates and applies them in one go.

    • So, even if you increment the counter five times, the value will only update once in the final render.

  4. Handling Multiple Updates:

    • If you need to increment the counter based on its current value multiple times (e.g., adding five), using a callback function in the state updater is effective.

    • With a callback function, React processes each update based on the most recent state value, ensuring that all intended updates are applied.

  5. Callback Function:

    • To ensure multiple increments are handled correctly, use a callback with the setState function. This callback receives the previous state, applies the update, and ensures accurate state changes.

Key Takeaway: React’s batching mechanism with Fiber and Virtual DOM ensures efficient updates, applying state changes in a single render. For multiple updates, use a callback function to handle each update based on the latest state.

10
Subscribe to my newsletter

Read articles from Vishesh Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vishesh Gupta
Vishesh Gupta