Popular Searches
Popular Course Categories
Popular Courses

State and Component Re-rendering

State and Component Re-rendering

State Management with useState

State and Component Re-rendering in React JS

Course: React JS Training

Topic: Understanding State, Component Rendering, Re-rendering, State Updates, and React UI Behaviour

Learning Objective: By the end of these notes, learners will understand how React state works, why components re-render, what happens after a state update, how parent and child components behave, and how to write efficient React components.


1. Introduction to State and Component Re-rendering

React is a JavaScript library used to build interactive user interfaces. Modern web applications frequently display changing information, such as counters, form inputs, product quantities, shopping carts, menus, and notifications.

To manage changing information, React provides a feature called state. When state changes through its setter function, React schedules a new render so the component can calculate the latest user interface.

Component re-rendering means React calls a component function again to determine what the interface should look like with the latest state, props, and context. React then updates the DOM only where necessary.

Example

Imagine a counter displaying the number 0. When a user clicks the Increment button, the number becomes 1. React updates the counter's state, renders the component again, and updates the displayed number.

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

Initially, the counter displays 0. Each click requests a state update, and React renders the component using the updated count.


2. What Is State in React?

State is component-specific information that React preserves between renders. It allows a component to remember values and display updated information when users interact with the application.

In function components, state is commonly managed using the useState Hook.

Syntax of useState

const [state, setState] = useState(initialValue);
  • state: The current state value available during the current render.
  • setState: The setter function used to request a state update.
  • initialValue: The value used to initialize the state when the component is mounted.

Example: Managing a Name

import { useState } from "react";
function Greeting() {
  const [name, setName] = useState("Alex");
  return (
    <div>
      <h2>Hello, {name}!</h2>
      <button onClick={() => setName("Sam")}>
        Change Name
      </button>
    </div>
  );
}
export default Greeting;

When the button is clicked, React receives a request to change the name from Alex to Sam. The component re-renders and displays the updated greeting.

Common Examples of State

  • Counter values.
  • Text entered into form fields.
  • Whether a menu is open or closed.
  • Whether a modal or dialog is visible.
  • Selected products and shopping cart items.
  • Loading indicators and error messages.
  • Selected tabs, filters, and pagination values.

3. What Is Rendering in React?

Rendering is the process in which React calls a component and calculates the JSX that represents the interface for the current set of inputs.

For a function component, rendering involves executing the component function and evaluating its returned JSX. Rendering does not automatically mean that React will modify the browser DOM.

Example

function Welcome() {
  const name = "Alex";
  return <h1>Welcome, {name}!</h1>;
}

When React renders this component, it evaluates the JSX and determines that the interface should display the heading “Welcome, Alex!”.

Initial Render

The initial render occurs when React first renders a component as part of displaying the application. React evaluates the component and commits the required DOM elements to the page.

Subsequent Render

A subsequent render occurs after the initial render when React needs to calculate the interface again, for example because state changes or a parent component re-renders.


4. What Is Component Re-rendering?

Component re-rendering is the process of calling a component function again to calculate its latest UI. React uses the current state, props, and context available during that render.

Re-rendering is an essential part of React's declarative approach. Instead of manually changing every affected DOM element, developers describe the interface they want for a given state, and React manages the necessary updates.

Example

import { useState } from "react";
function ToggleMessage() {
  const [visible, setVisible] = useState(false);
  return (
    <div>
      <button onClick={() => setVisible(!visible)}>
        Toggle Message
      </button>
      {visible && <p>Welcome to React!</p>}
    </div>
  );
}

Initially, the message is hidden because visible is false. When the user clicks the button, the state changes and React renders the component again. The message then appears. Clicking the button again hides it.

Important Point

A re-render does not mean the entire web page is recreated. React calculates the latest output and commits only the DOM changes that are necessary.


5. Main Reasons Why a React Component Re-renders

5.1 State Update

When a component's state is updated using a setter such as setCount, React schedules a render. If the next state is equal to the previous state according to Object.is, React may skip the component's rendering work.

const [count, setCount] = useState(0);
function increaseCount() {
  setCount(count + 1);
}

When the count changes from 0 to 1, React can render the component with the new value.

5.2 Parent Component Re-renders

When a parent component re-renders, React normally also renders its child components as it processes the updated component tree. This can happen even when a child's props appear unchanged, unless an applicable optimization allows React to skip that work.

function Parent() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        Parent Count: {count}
      </button>
      <Child />
    </div>
  );
}
function Child() {
  return <p>I am a child component.</p>;
}

When the parent's count changes, the parent re-renders. React also normally calls the Child component again because it is part of the parent’s rendered tree.

5.3 Props Change

Props are values passed from a parent to a child component. When a parent re-renders and provides new props, React can render the child with those new values.

function Parent() {
  const [name, setName] = useState("Alex");
  return (
    <div>
      <button onClick={() => setName("Sam")}>
        Change Name
      </button>
      <Child name={name} />
    </div>
  );
}
function Child({ name }) {
  return <h2>Hello, {name}!</h2>;
}

When the name changes, the child receives the updated prop and renders the new greeting.

5.4 Context Value Changes

Components that read a context value using useContext can re-render when that context value changes. Context is useful for sharing information such as a theme, locale, or authenticated user across a component tree.

5.5 External Store Updates

Components that subscribe to external stores using supported React subscription mechanisms can re-render when the relevant store data changes. For example, a component using useSyncExternalStore can update in response to a subscribed store snapshot changing.

Summary Table

Cause What Happens Example
State update React schedules the component to render again. Incrementing a counter.
Parent re-render Child components are normally rendered as React processes the tree. Changing a parent's local state.
Props change The child can render with the latest props. Changing a displayed username.
Context change Consumers of the changed context can re-render. Switching the application theme.
External store update Subscribed components can render with the latest snapshot. Updating shared store data.

6. Understanding the React Render Cycle

React describes a screen update using three main steps: triggering a render, rendering components, and committing changes to the DOM.

Step 1: Trigger a Render

A render can be triggered by the initial rendering of the application or by an update, such as a state setter being called with a different value.

Step 2: Render the Components

React calls the relevant component functions to calculate what the UI should look like with the latest values. Components should remain pure during rendering: they should calculate their output without modifying existing data or performing side effects.

Step 3: Commit Changes to the DOM

React compares the newly calculated output with the previous output and commits the necessary changes to the browser DOM. If the output has not changed, React may not need to modify the DOM.

Render Cycle Flow

User interacts with the application
             |
             v
State setter is called
             |
             v
React schedules an update
             |
             v
React renders the component
             |
             v
React compares the latest output
             |
             v
Necessary DOM changes are committed
             |
             v
Browser displays the updated interface

Remember: A component function being called again and the browser DOM being modified are two different things.


7. How useState Triggers Re-rendering

The useState Hook allows a function component to store a value between renders and request an update when that value changes.

Example: Counter Component

import { useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  const handleIncrement = () => {
    setCount(previousCount => previousCount + 1);
  };
  return (
    <section>
      <h2>Counter Application</h2>
      <p>Current Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
    </section>
  );
}
export default Counter;

How It Works

  1. React initializes the count state to 0 when the component is mounted.
  2. The component renders and displays “Current Count: 0”.
  3. The user clicks the Increment button.
  4. The event handler calls the setter with an updater function.
  5. React processes the state update and renders the component with the new count.
  6. The UI displays the updated count.

The functional updater form is useful when the next state depends on the previous state. React can process queued updater functions in order.


8. State Is a Snapshot of Each Render

One important React concept is that state behaves like a snapshot. A component's state variables belong to the render in which the component function was executed.

Calling a state setter requests a future render; it does not change the state variable inside the currently running function.

Example

import { useState } from "react";
function SnapshotExample() {
  const [count, setCount] = useState(0);
  function handleClick() {
    setCount(count + 1);
    console.log(count);
  }
  return (
    <button onClick={handleClick}>
      Count: {count}
    </button>
  );
}

If the count is 0 when the button is clicked, the console statement inside that event handler still logs 0. The next render will use the updated count of 1.

Why Does This Happen?

  • The event handler belongs to the render in which it was created.
  • Its variables continue to represent that render's state snapshot.
  • The setter requests an update for a subsequent render.
  • The next render receives the new state value.

Do not assume that reading a state variable immediately after calling its setter will return the new value.


9. Updating State Correctly to Trigger Re-rendering

React state should be updated using its setter function. Do not mutate state directly because React may not detect a meaningful change when the same object or array reference is passed back.

Incorrect: Updating a Normal Variable

function Counter() {
  let count = 0;
  function increase() {
    count = count + 1;
  }
  return (
    <button onClick={increase}>
      Count: {count}
    </button>
  );
}

This approach does not work as intended. A local variable does not persist as component state between renders, and changing it does not tell React to render the component again.

Correct: Using useState

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

Incorrect: Mutating an Object

const [user, setUser] = useState({ name: "Alex" });
user.name = "Sam";
setUser(user);

This mutates the existing object and passes the same reference to the setter. React may ignore the update because the new value is equal to the old reference.

Correct: Creating a New Object

setUser(previousUser => ({
  ...previousUser,
  name: "Sam"
}));

Creating a new object gives React a new reference and follows the recommended immutable state-update pattern.


10. Difference Between Rendering and Re-rendering

Feature Initial Rendering Re-rendering
Meaning The component is rendered for the first time in its current mounted lifecycle. The component is rendered again to calculate updated UI.
Typical trigger React begins displaying the application or mounting the component. State, parent updates, props, context, or a subscribed store change.
DOM behaviour React commits the required initial DOM elements. React commits only the necessary DOM changes.
State behaviour Initial state values are established for the mounted component. React uses the current state values for that render.
Example Displaying a counter with a value of 0. Displaying the counter after it increases to 1.

11. Parent and Child Component Re-rendering

React applications commonly contain nested components. When a parent component re-renders, React normally processes its child components again as part of rendering the updated tree.

Example

import { useState } from "react";
function Parent() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h2>Parent Component</h2>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase Count
      </button>
      <Child />
    </div>
  );
}
function Child() {
  console.log("Child rendered");
  return <p>This is the child component.</p>;
}
export default Parent;

Clicking the button changes the parent's state. The Parent function renders again, and React normally calls Child again because it is rendered within Parent.

Can Child Re-rendering Be Skipped?

In suitable cases, React's memo API can skip a child component's re-render when its props have not changed according to the comparison used by memo. However, memo is an optimization, not a guarantee that the component will never re-render.

import { memo, useState } from "react";
function Parent() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        Count: {count}
      </button>
      <Child name="Alex" />
    </div>
  );
}
const Child = memo(function Child({ name }) {
  console.log("Child rendered");
  return <p>Hello, {name}!</p>;
});
export default Parent;

In this example, Child can skip re-rendering when the parent count changes because its string prop remains unchanged. The component may still re-render when its own state or a context value it uses changes.


12. Does Every Re-render Update the DOM?

No. Rendering and DOM updates are separate stages. React can call a component again, calculate its JSX, and determine that the browser DOM does not need to change.

Example

function Message() {
  return <h2>Welcome to React</h2>;
}

If React renders this component again and the output is identical, there may be no DOM changes to commit. This is one reason not to equate a re-render with rebuilding the entire page.

Important Distinctions

  • Component render: React calls a component to calculate its output.
  • Reconciliation: React determines how the latest output relates to the previous output.
  • DOM commit: React applies the necessary DOM changes.
  • Browser paint: The browser draws the visual result on screen.

13. State Updates and Batching

React can batch multiple state updates so that several updates made during the same event are processed together. This helps avoid unnecessary rendering work.

Example: Multiple State Updates

import { useState } from "react";
function Profile() {
  const [name, setName] = useState("Alex");
  const [age, setAge] = useState(20);
  function updateProfile() {
    setName("Sam");
    setAge(25);
  }
  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <button onClick={updateProfile}>
        Update Profile
      </button>
    </div>
  );
}

React generally batches these updates in modern React, allowing the component to render with the updated name and age together instead of committing a separate render for each setter call.

Functional State Updates

When several updates depend on the previous value, use functional updater functions to ensure each update is calculated from the latest queued state.

function increaseThreeTimes() {
  setCount(previous => previous + 1);
  setCount(previous => previous + 1);
  setCount(previous => previous + 1);
}

When processed together, these updater functions increase the count by three.


14. Common Mistakes Related to Re-rendering

Mistake 1: Expecting a Local Variable to Trigger a Render

let total = 0;
total = total + 1;

Problem: Updating a normal variable does not request a React render.

Solution: Use useState when a value needs to persist between renders and affect the UI.

Mistake 2: Calling a Setter Unconditionally During Rendering

function Example() {
  const [count, setCount] = useState(0);
  setCount(count + 1);
  return <p>{count}</p>;
}

Problem: Setting state unconditionally during rendering can cause an infinite re-render loop and the “Too many re-renders” error.

Solution: Update state in event handlers or other appropriate places. Avoid unconditional state updates during rendering.

Mistake 3: Calling the Event Handler Immediately

<button onClick={setCount(count + 1)}>
  Increase
</button>

Problem: This calls the setter while rendering instead of waiting for a click.

Solution: Pass a function as the event handler.

<button onClick={() => setCount(count + 1)}>
  Increase
</button>

Mistake 4: Mutating State Directly

items.push("New Item");
setItems(items);

Problem: The existing array is mutated, and the same reference is passed back to the setter.

Solution: Create a new array.

setItems(previousItems => [...previousItems, "New Item"]);

Mistake 5: Assuming Every Parent Update Must Change the DOM

Problem: A component may re-render even if its displayed output remains the same.

Solution: Understand the difference between a component render and a DOM commit. Optimize only when there is a meaningful performance need.

Mistake 6: Using State for Values That Can Be Calculated

Problem: Storing redundant derived values can introduce extra state updates and inconsistent UI.

Solution: Calculate values from existing state and props when possible.

const [price, setPrice] = useState(100);
const [quantity, setQuantity] = useState(2);
const total = price * quantity;

Here, total can be calculated during rendering, so it does not need a separate state variable.


15. Best Practices for State and Re-rendering

  • Use useState for values that need to persist between renders and affect the UI.
  • Update state using the setter function rather than assigning to the state variable directly.
  • Use functional updates when the next state depends on the previous state.
  • Never mutate objects or arrays held in state; create replacement values instead.
  • Keep component rendering pure and free of side effects.
  • Do not call state setters unconditionally during rendering.
  • Keep state as local to the components that need it as practical.
  • Use props to pass data from parent components to child components.
  • Use context when multiple components need access to shared information.
  • Do not assume that every render changes the DOM.
  • Use memo, useMemo, or useCallback only when appropriate and when they address an actual performance concern.
  • Use the React Developer Tools Profiler to investigate unnecessary rendering work.
  • Do not rely on a component rendering exactly once. Development Strict Mode may invoke rendering logic more than once to help detect impure code.

16. Practical Project: Counter with Re-rendering

This small project demonstrates how state updates cause a component to render with the latest value.

Complete Code

import { useState } from "react";
function CounterApp() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h1>Counter Application</h1>
      <h2>Current Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
      <button onClick={() => setCount(count - 1)}>
        Decrease
      </button>
      <button onClick={() => setCount(0)}>
        Reset
      </button>
    </div>
  );
}
export default CounterApp;

Project Explanation

  1. The initial state is 0.
  2. The Increase button requests a state update that adds 1.
  3. The Decrease button requests a state update that subtracts 1.
  4. The Reset button requests a state update that sets the value to 0.
  5. React renders the component with the new count whenever the state changes.
  6. React commits the necessary UI changes to display the latest count.

Expected Output

Action Count Before Count After
Initial display — 0
Click Increase 0 1
Click Increase 1 2
Click Decrease 2 1
Click Reset 1 0

17. Practical Project: Show and Hide a Message

This example demonstrates conditional rendering in response to a state change.

import { useState } from "react";
function MessageApp() {
  const [showMessage, setShowMessage] = useState(false);
  return (
    <div>
      <h1>Message Application</h1>
      <button onClick={() => setShowMessage(previous => !previous)}>
        {showMessage ? "Hide Message" : "Show Message"}
      </button>
      {showMessage && <p>React re-rendered the component!</p>}
    </div>
  );
}
export default MessageApp;

How It Works

  • The initial state is false, so the message is not displayed.
  • Clicking the button changes the state to true.
  • React renders the component using the new state.
  • The message appears and the button label changes.
  • Clicking again changes the state back to false, hiding the message.

18. React Strict Mode and Re-rendering

React Strict Mode is a development-only tool that helps identify potential problems in a React application. In supported development configurations, it may call component functions more than once to help reveal impure rendering logic.

This extra development behaviour does not mean that every production render will happen twice. When debugging, distinguish development-only Strict Mode behaviour from normal application updates.

Example

function Example() {
  console.log("Component rendered");
  return <h2>Hello React</h2>;
}

If you see the log more than once in development, check whether Strict Mode is enabled and whether another update is causing a render. A console message alone does not prove that the browser DOM was updated twice.


19. Performance Optimization and Re-rendering

Re-rendering is a normal feature of React. It is not automatically a problem. Optimization is useful when rendering work becomes expensive or affects user experience.

19.1 React.memo

memo can let React skip rendering a component when its props have not changed according to the memo comparison and no other update requires it to render.

import { memo } from "react";
const UserCard = memo(function UserCard({ name }) {
  return <h2>User: {name}</h2>;
});
export default UserCard;

19.2 useMemo

useMemo caches the result of a calculation between renders while its dependencies remain unchanged. It can help when a calculation is expensive.

const total = useMemo(() => {
  return products.reduce((sum, product) => sum + product.price, 0);
}, [products]);

19.3 useCallback

useCallback caches a function definition between renders while its dependencies remain unchanged. It can be useful when passing callbacks to memoized children or when another Hook depends on a stable function reference.

const handleClick = useCallback(() => {
  setCount(previous => previous + 1);
}, []);

Optimization Guidelines

  • Measure performance before adding optimizations.
  • Prefer simple, readable components.
  • Keep unrelated state separate when it helps avoid unnecessary coupling.
  • Use memoization only when it provides a practical benefit.
  • Remember that memoized components can still render because of their own state or context updates.

20. Real-World Uses of State and Re-rendering

Application State Example Re-rendering Behaviour
E-commerce website Cart quantity Displays updated product quantity and totals.
Login form Email and password fields Updates controlled input values as the user types.
Weather application Current weather data Displays the latest data after it is loaded into state.
To-Do application Task list Shows newly added, completed, or removed tasks.
Dashboard Selected filters Renders the interface for the selected filter values.
Navigation menu Open or closed status Displays or hides the menu based on the state.
Image gallery Current image index Displays the selected image after navigation.
Theme settings Light or dark theme Updates components that consume the changed theme.

21. Interview Questions and Answers

Q1. What is state in React?

Answer: State is component-specific information that React preserves between renders. It can be updated using a setter function such as the function returned by useState.

Q2. What is component re-rendering?

Answer: Component re-rendering is when React calls a component function again to calculate the latest UI using the current state, props, and context.

Q3. What are the common reasons for re-rendering?

Answer: Common reasons include state updates, parent component renders, changed props, context changes, and updates from subscribed external stores.

Q4. Does every re-render update the DOM?

Answer: No. React may render a component and determine that no DOM changes are necessary. It commits only the changes required to match the latest UI.

Q5. What happens when a state setter is called?

Answer: React queues or schedules the state update. The component can then render using the updated state value.

Q6. Why does a normal variable not trigger re-rendering?

Answer: Changing a normal variable does not notify React that the UI needs to be updated, and local variables do not persist as component state between renders.

Q7. Why should state objects not be mutated directly?

Answer: Mutating an existing object or array can preserve the same reference, which may cause React to ignore an update. Create a new object or array instead.

Q8. What is the difference between render and commit?

Answer: Rendering calculates what the UI should look like. Committing applies the necessary changes to the DOM.

Q9. What is React.memo?

Answer: memo is an optimization that can skip a component's re-render when its props have not changed according to the comparison and no other update requires a render.

Q10. What is state batching?

Answer: Batching means React processes multiple state updates together where appropriate, reducing unnecessary rendering work.

Q11. Why might a component render twice in development?

Answer: React Strict Mode may call rendering logic more than once in development to help detect impure code. This is not a guarantee that production rendering happens twice.

Q12. How can you avoid an infinite re-render loop?

Answer: Do not call state setters unconditionally during rendering. Update state in event handlers or other appropriate locations, and make sure event handlers are passed as functions rather than executed immediately.


22. Practice Exercises

  1. Create a counter that increments and decrements using useState.
  2. Create a button that toggles a message between visible and hidden.
  3. Create a form with a controlled name input and display a live greeting.
  4. Create a parent component with a state value and a child component that receives that value through props.
  5. Use console.log to observe component function calls during state updates.
  6. Write an example that updates an array in state without mutating it.
  7. Display a calculated total using two state variables without storing the total separately.
  8. Experiment with memo and compare child rendering when props stay the same.

23. Quick Revision Checklist

  • State stores information between renders.
  • useState provides the current state and a setter function.
  • Calling a setter requests a state update and can trigger a re-render.
  • State values behave like snapshots belonging to individual renders.
  • Parent updates can cause child components to render again.
  • Props and context changes can cause affected components to re-render.
  • Rendering and DOM commits are separate steps.
  • React only commits the DOM changes that are necessary.
  • State objects and arrays should be updated immutably.
  • Functional state updates are useful when the next value depends on the previous value.
  • React can batch multiple state updates.
  • Memoization should be used thoughtfully, based on actual performance needs.

24. Official React Documentation


25. React JS Training and Course Demo

To learn more about React components, Hooks, state management, event handling, conditional rendering, and building interactive applications, explore the following training resources.

React JS Training Course: JustAcademy React JS Training Course

Register for a Course Demo: Register for React JS Course Demo


Conclusion

State and component re-rendering are fundamental concepts in React JS. State allows a component to remember information, while re-rendering enables React to calculate the UI again when relevant inputs change. React then commits only the necessary DOM changes. Understanding the render cycle, state snapshots, parent-child behaviour, immutable updates, batching, and performance optimization helps developers build interactive, predictable, and maintainable React applications.

Previous Next
whatsapp