Popular Searches
Popular Course Categories
Popular Courses

Understanding Re-rendering

Understanding Re-rendering

React Performance Optimization

Understanding Re-rendering in React – Detailed Notes

Course: React JS Training

Topic: Understanding component re-rendering, state updates, props changes, parent-child rendering, performance optimization, React.memo, useMemo, useCallback, and practical examples.


1. Introduction to Re-rendering

Re-rendering is the process in which React calls a component again to calculate what the user interface should look like based on its latest state, props, and context.

When information in a React application changes, the interface may need to display updated content. React re-renders components to calculate the new UI and then updates the DOM only where necessary.

For example, when a user clicks a counter button, the displayed number changes. React re-renders the component to calculate the updated output.

Official documentation: React Render and Commit

2. What Is Re-rendering?

Re-rendering means React executes a component again to determine the latest UI output. It does not necessarily mean that the entire webpage or DOM is recreated.

React compares the new output with the previous output and applies the necessary DOM changes during the commit phase.

Example: If a component displays a counter value of 5 and its state changes to 6, React calculates the updated output and changes the displayed number when necessary.

3. Rendering vs Re-rendering

Feature Rendering Re-rendering
Meaning Calculating the UI output for a component. Calculating the UI output again after an update.
When it happens During the initial display of the component. When an update triggers another render.
Common triggers Initial application rendering. State updates, parent renders, and relevant context changes.
DOM behavior React creates and inserts the required DOM nodes. React updates only the necessary DOM changes.
Purpose Display the initial UI. Keep the UI synchronized with updated data.

4. Main Reasons for Re-rendering

React components can re-render for several reasons.

4.1 State Changes

When a component updates its state using a setter function such as setCount(), React schedules a render.

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

export default Counter;

Explanation:

  • The initial state is 0.
  • When the button is clicked, the state update is requested.
  • React renders the component again with the updated count.
  • The displayed number changes to reflect the new state.

4.2 Props Changes

Props are values passed from a parent component to a child component. When the parent renders and passes updated props, the child may re-render to calculate its new UI.

function Greeting({ name }) {
  return <h2>Hello, {name}!</h2>;
}

function App() {
  return <Greeting name="Rahul" />;
}

export default App;

If the parent later passes a different name, the Greeting component can render the updated message.

4.3 Parent Component Re-renders

When a parent component re-renders, React normally also renders its child components as it processes the updated component tree. A child can sometimes skip rendering when an optimization such as React.memo applies and its relevant inputs have not changed.

import { useState } from 'react';

function Child() {
  console.log('Child rendered');
  return <p>This is the child component.</p>;
}

function Parent() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
      <Child />
    </div>
  );
}

export default Parent;

Explanation: Clicking the button updates the parent's state. React renders the parent again and normally renders the Child component as part of that process.

4.4 Context Changes

When a component reads a context value using useContext(), it can re-render when the value provided by the nearest matching context provider changes.

import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext('light');

function ThemeDisplay() {
  const theme = useContext(ThemeContext);

  return <p>Current theme: {theme}</p>;
}

function App() {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext value={theme}>
      <ThemeDisplay />
      <button
        onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
      >
        Change Theme
      </button>
    </ThemeContext>
  );
}

export default App;

Explanation: Changing the theme updates the context value. The ThemeDisplay component reads that value, so React updates its rendered output when the context changes.

5. Understanding the React Render Cycle

React generally processes UI updates through three main steps.

  1. Trigger: An initial render or an update schedules rendering.
  2. Render: React calls components to calculate the next UI output.
  3. Commit: React applies the necessary changes to the DOM.

After React commits DOM changes, the browser may paint the updated screen.

User interaction or update
          |
          v
State, props, or context update
          |
          v
React renders affected component tree
          |
          v
React calculates necessary DOM changes
          |
          v
React commits changes to the DOM
          |
          v
Browser displays the updated interface

Important: A render does not always lead to a DOM change. If the calculated output is effectively the same, React may not need to modify the DOM.

6. Re-rendering with useState()

The useState() Hook lets a function component store information that can change over time. Calling its setter requests a state update.

import { useState } from 'react';

function Toggle() {
  const [isVisible, setIsVisible] = useState(true);

  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        Toggle Message
      </button>

      {isVisible && <p>Hello, React!</p>}
    </div>
  );
}

export default Toggle;

When the button is clicked, the state changes and React renders the component again. The paragraph is displayed or removed according to the latest state.

7. Re-rendering with Props

A child component receives props from its parent. When a parent supplies new prop values, React can render the child with those values.

import { useState } from 'react';

function User({ name }) {
  return <h3>User: {name}</h3>;
}

function App() {
  const [name, setName] = useState('Amit');

  return (
    <div>
      <User name={name} />
      <button onClick={() => setName('Priya')}>
        Change User
      </button>
    </div>
  );
}

export default App;

Initially, the page displays Amit. Clicking the button changes the parent's state, which changes the prop passed to User. The child then displays Priya.

8. Does Every Re-render Update the DOM?

No. React may call a component again without changing any DOM nodes. Rendering calculates the desired output, while the commit phase applies actual DOM changes only where needed.

For example, if a parent component re-renders but a child returns the same text and structure, React may have no DOM changes to apply for that child.

Keep these concepts separate:

  • Component render: React executes the component to calculate its output.
  • DOM update: React applies changes to browser DOM nodes when required.
  • Browser paint: The browser draws the visual result on the screen.

9. Preventing Unnecessary Re-renders with React.memo()

React.memo() is a performance optimization that can allow a function component to skip rendering when its props have not changed according to React's default shallow comparison.

import { memo, useState } from 'react';

const User = memo(function User({ name }) {
  console.log('User rendered');

  return <h3>Hello, {name}!</h3>;
});

function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        Count: {count}
      </button>

      <User name="Rahul" />
    </div>
  );
}

export default App;

Explanation:

  • The parent re-renders when count changes.
  • The User component receives the same string prop, "Rahul".
  • React.memo may skip rendering User because its props have not changed.
  • User can still re-render when its own state or a context it reads changes.

Note: React.memo is an optimization, not a guarantee that React will never render the component again.

10. Understanding useMemo()

The useMemo() Hook caches the result of a calculation between renders until one of its dependencies changes. It can be useful when a calculation is expensive or when a stable object value is important for a memoized child.

import { useMemo, useState } from 'react';

function ProductList({ products, search }) {
  const filteredProducts = useMemo(() => {
    return products.filter(product =>
      product.name.toLowerCase().includes(search.toLowerCase())
    );
  }, [products, search]);

  return (
    <ul>
      {filteredProducts.map(product => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

function App() {
  const [search, setSearch] = useState('');

  const products = [
    { id: 1, name: 'Laptop' },
    { id: 2, name: 'Mobile' },
    { id: 3, name: 'Headphones' }
  ];

  return (
    <div>
      <input
        value={search}
        onChange={event => setSearch(event.target.value)}
        placeholder="Search products"
      />
      <ProductList products={products} search={search} />
    </div>
  );
}

export default App;

Explanation: The filtered list is recalculated when products or search changes. In this particular example, the products array is created inside App, so its reference changes on every App render. For a stable dependency, define static data outside the component or memoize it when appropriate.

11. Understanding useCallback()

The useCallback() Hook caches a function definition between renders until its dependencies change. It can help when passing callbacks to memoized child components.

import { memo, useCallback, useState } from 'react';

const Button = memo(function Button({ onClick }) {
  console.log('Button rendered');

  return <button onClick={onClick}>Click Child</button>;
});

function App() {
  const [count, setCount] = useState(0);

  const handleChildClick = useCallback(() => {
    console.log('Child button clicked');
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase Count
      </button>
      <Button onClick={handleChildClick} />
    </div>
  );
}

export default App;

Because the callback reference remains stable, React.memo can skip rendering Button when its other props also remain unchanged. Use this optimization when it provides a meaningful benefit rather than applying it to every function automatically.

12. Common Causes of Unnecessary Re-renders

  • Updating state at a component level that is higher in the tree than necessary.
  • Passing newly created object or array references to memoized children on every render.
  • Creating new callback functions for children when stable references would be useful.
  • Updating state even when the intended value has not changed.
  • Using context providers whose values change more frequently than their consumers need.
  • Rendering large component trees without checking whether performance is actually a problem.

13. How to Optimize Re-rendering

  1. Keep state local: Store state close to the components that need it.
  2. Use React.memo: Consider it for expensive components that frequently receive unchanged props.
  3. Use useMemo: Cache expensive calculations when measurements show a benefit.
  4. Use useCallback: Keep callback references stable when it helps memoized children or dependency management.
  5. Split large components: Break complex UI into smaller components with clear responsibilities.
  6. Keep context focused: Separate unrelated context values when broad updates cause unnecessary work.
  7. Avoid direct mutation: Use state setters and immutable updates instead of changing state objects directly.
  8. Measure first: Use React Developer Tools Profiler to identify expensive or frequent renders before optimizing.

14. Common Mistakes Related to Re-rendering

Mistake 1: Mutating State Directly

// Incorrect
user.name = 'Priya';
setUser(user);

This mutates an existing object and passes the same reference back. React may skip the update because the state value is identical by reference.

Correct approach:

setUser(previousUser => ({
  ...previousUser,
  name: 'Priya'
}));

Mistake 2: Updating State During Every Render

// Incorrect pattern
function App() {
  const [count, setCount] = useState(0);
  setCount(count + 1);

  return <p>{count}</p>;
}

Updating state unconditionally during rendering can cause repeated renders and an infinite render loop.

Correct approach: Update state in an event handler or an appropriate effect when synchronizing with an external system.

function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

Mistake 3: Expecting State to Change Immediately

function handleClick() {
  setCount(count + 1);
  console.log(count);
}

The logged value belongs to the current render and may still be the previous count. The setter requests an update for a subsequent render.

Mistake 4: Expecting React.memo to Block Every Render

React.memo primarily compares props. A memoized component may still render when its own state changes or when a context it uses changes.

15. Re-rendering and React Strict Mode

In development, React Strict Mode may call component functions more than once to help identify impure rendering logic. This behavior is intended to expose bugs and is not necessarily evidence of a production performance issue.

Components should render purely: given the same props, state, and context, they should calculate the same output without causing side effects.

Official documentation: React StrictMode Documentation

16. Practical Project: Counter with Re-render Tracking

Objective: Build a counter and observe when the parent and child components render.

import { memo, useState } from 'react';

const Message = memo(function Message({ text }) {
  console.log('Message component rendered');
  return <p>{text}</p>;
});

function App() {
  const [count, setCount] = useState(0);

  console.log('App component rendered');

  return (
    <div>
      <h1>Re-render Demo</h1>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
      <Message text="This message stays the same." />
    </div>
  );
}

export default App;

Expected Behavior

  1. The App component renders initially.
  2. The Message component renders initially.
  3. Clicking Increase updates the counter and re-renders App.
  4. Message can skip re-rendering because its text prop remains unchanged and it is wrapped in React.memo.

Development note: Strict Mode may cause extra render logs during development. Evaluate the component behavior in the correct development or production context.

17. Interview Questions and Answers

Q1. What is re-rendering in React?

Re-rendering is the process of executing a component again to calculate the latest UI output after an update.

Q2. What are the main causes of re-rendering?

Common causes include state updates, parent renders, changed props, and context changes used by the component.

Q3. Does every re-render update the DOM?

No. React may render a component without applying any DOM changes if the output does not require them.

Q4. What is React.memo?

React.memo is a performance optimization that can skip rendering a function component when its props have not changed according to its comparison.

Q5. What is the difference between useMemo and useCallback?

useMemo caches a calculated value, while useCallback caches a function definition.

Q6. Why should state not be mutated directly?

Direct mutation can prevent React from detecting an intended change and can lead to inconsistent UI behavior. Use the appropriate state setter and immutable updates.

Q7. Can a memoized component re-render when context changes?

Yes. React.memo does not prevent re-renders caused by changes to context that the component reads.

Q8. Why might a component render twice in development?

React Strict Mode may call components more than once in development to help detect impure rendering logic.

Q9. How can unnecessary re-renders be reduced?

Keep state local, split components appropriately, use memoization when useful, avoid unnecessary reference changes, and profile performance.

Q10. What is the difference between rendering and committing?

Rendering calculates the desired UI output. Committing applies the necessary changes to the DOM.

18. Quick Revision Checklist

  • Understand rendering and re-rendering.
  • Know how state updates trigger rendering.
  • Understand how props, parents, and context affect rendering.
  • Distinguish a component render from an actual DOM update.
  • Practice React.memo, useMemo, and useCallback.
  • Avoid direct state mutation and unconditional state updates during rendering.
  • Understand development-only Strict Mode behavior.
  • Use React Developer Tools Profiler before applying performance optimizations.

19. Learning Resources and Course Links

Conclusion

Understanding re-rendering is essential for building efficient React applications. State updates, props, parent renders, and context changes can trigger components to render again. React calculates the latest UI and applies only the necessary DOM changes. By keeping state local, writing pure components, and using React.memo, useMemo, and useCallback when appropriate, developers can improve performance without introducing unnecessary complexity.

Previous Next
whatsapp