achal_tiwari

Achal Tiwari

Posted on July 3, 2024

React 101

This article assumes familiarity with React coding, particularly in using states and other essential features.

State

  • State: Component-specific memory in React used to track and manage dynamic data within a component.
  • Dynamic Interaction: State allows components to change what’s displayed on the screen based on user interactions or other events.

Common Use Cases

  1. Form Inputs: State is used to remember and update the current value of an input field as a user types.
  2. Image Carousels: State tracks the currently displayed image and updates it when the user clicks “next” or “previous”.
  3. Shopping Carts: State manages the items in the shopping cart, adding new products when the user clicks “buy”.

React batches state updates. It updates the screen after all the event handlers have run and have called their set functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier use flushSync.

Queuing a Series of State Updates

Setting a state variable will queue another render. But sometimes you might want to perform multiple operations on the value before queuing the next render

// This is a general Interview question
import { useState } from 'react';
export default function Counter() {
  const [number, setNumber] = useState(0);
  return (
    <>
    // M-1
      <h1>{number}</h1>
      <button onClick={() => {
        setNumber(number + 1);
        setNumber(number + 1);
        setNumber(number + 1);
      }}>+3</button>
    // M-2
      <h1>{number}</h1>
      <button onClick={() => {
        setNumber(n => n + 1);
        setNumber(n => n + 1);
        setNumber(n => n + 1);
      }}>+3</button>
    </>

  )
}
Enter fullscreen mode Exit fullscreen mode

I want you to think about how will M-1 and M-2 perform.

M-1 code will only increment the number by 1

Why?

Each render’s state values are fixed, so the value of number inside the first render’s event handler is always 0, no matter how many times you call setNumber(1):

  • React waits until all code in the event handlers has run before processing your state updates. This is why the re-render only happens after all these setNumber() calls.

But M-2 code can do the increment by 3

Why?

Here, n => n + 1 is called an updater function. When you pass it to a state setter:

  1. React queues this function to be processed after all the other code in the event handler has run.
  2. During the next render, React goes through the queue and gives you the final updated state.

This is the first part of my React series, covering some basics. Follow me for more upcoming parts! If you have any queries, drop a comment—I'll do my best to provide answers.

💖 💪 🙅 🚩
achal_tiwari
Achal Tiwari

Posted on July 3, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related