"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Understanding Rendering and Rerendering in React Applications: How They Work and How to Optimize Them

Understanding Rendering and Rerendering in React Applications: How They Work and How to Optimize Them

Published on 2024-11-03
Browse:976

Razumevanje Renderovanja i Rerenderovanja u React Aplikacijama: Kako funkcionišu i kako ih optimizovati

When we create applications in React, we often come across the terms rendering and re-rendering components. Although this may seem simple at first glance, things get interesting when different state management systems like useState, Redux, or when we insert lifecycle hooks like useEffect are involved. If you want your application to be fast and efficient, understanding these processes is key.

What is Rendering?

Rendering is the process by which React renders your user interface (UI) on screen, based on state or props. When your component is rendered for the first time, it's called the first render.

How Does Initial Render Work?

When a component is first "mounted" to the DOM, this is what happens:

1. State initialization:
Whether you use useState, props, or Redux, the initial state of the component is created.

2. Render function:
React loops through the JSX code and generates a virtual DOM based on the current state.

3. Creates a virtual DOM (Virtual DOM) for the current state of the component.

4. Comparing (diffing):
The virtual DOM is compared to the real DOM (since it is the first render, all elements will be fully rendered).

5. Showing:
The component is displayed on the screen.
Once the component is rendered, the next challenge is rerendering.

Re-rendering: When and Why?

Rerendering happens every time the state or props change. Did you click the button that changes the number on the screen? Changed a value in the Redux store? All of those actions can cause React to render the component again, and that's where rerendering comes in.

How Does Rerendering Work?

State change detection:

  • With useState, when you call setState, React knows it needs to update the component.

  • With Redux, when a value in the store changes, every component associated with that part of the state is re-rendered.

Render trigger:

When the state changes, React creates a new virtual DOM based on that change.

Comparing (diffing):

  • React compares the new virtual DOM with the old one and calculates which changes to apply. This is one way React optimizes rendering.

View changes:

  • After the changes are calculated, React applies them to the actual DOM. Thus, only the changed parts of the page are displayed again.

Which Components Are Rerendered?

Not all components are affected by every change. React rerenders only those components that:

Use local states:
If you use useState, the component is rerendered every time setState is called.

Use Redux state:
If your component depends on Redux state (via useSelector or connect), it will be re-rendered when that part of the state changes.

Use props:
If the props value changes, the component is re-rendered with the new values.

Optimization of Rendering

Of course, it is not always ideal to needlessly re-render all components. If we want the application to work quickly and efficiently, here are some optimization techniques:

1. Memoization Components
React offers functionality for component memoization via React.memo. If your component doesn't depend on props or state changes, you can "remember" it, so it will re-render only when the relevant values ​​change.

Example:

const MemoizedComponent = React.memo(MyComponent);

2. Memoization of Functions and Values

To avoid recreating functions or values ​​on every render, use useCallback to memoize functions and useMemo to memoize values.

  • useCallback allows you to memoize a function and prevent it from being recreated until the dependencies change.

  • useMemo memoizes the result of the function, so it is not recomputed on every render.

Example:

const increment = useCallback(() => {
  setCount(prevCount => prevCount   1);
}, []);

const expensiveCalculation = useMemo(() => {
  return count * 2;
}, [count]);

3. Redux Optimization

If you use Redux, you can further optimize the application with memoized selectors such as reselect. This makes it possible to avoid re-rendering components that are not affected by the state change.

Lifecycle Hooks and Rendering

In classic React classes, we used shouldComponentUpdate to control when the component will be re-rendered. In functional components, this concept can be simulated using useEffect and memoization.

Conclusion

Rendering and rerendering are crucial to UI display in React apps, but properly understanding and optimizing those processes can make the difference between a slow and super-fast app. Correct use of memoization, useCallback, useMemo, as well as careful handling of Redux, helps to avoid unnecessary re-renders and keep our applications fast and responsive.

Example Code: Rendering and Rerendering in Action
Here's an example of a component that uses useState, Redux, and memoization to optimize rendering:

import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useSelector, useDispatch } from 'react-redux';

const MyComponent = () => {
  // Lokalni state
  const [count, setCount] = useState(0);

  // Redux state
  const reduxValue = useSelector(state => state.someValue);
  const dispatch = useDispatch();

  // Memoizacija funkcije kako bi se izbeglo ponovno kreiranje na svakom renderu
  const increment = useCallback(() => {
    setCount(prevCount => prevCount   1);
  }, []);

  // Memoizacija izračunate vrednosti
  const expensiveCalculation = useMemo(() => {
    return count * 2;
  }, [count]);

  // Efekat koji se pokreće samo pri promeni reduxValue
  useEffect(() => {
    console.log("Redux value changed:", reduxValue);
  }, [reduxValue]);

  return (
    

Count: {count}

Expensive Calculation: {expensiveCalculation}

); };

As we can see, a combination of local state, Redux, memoization and useEffect hook is used here to make the application as efficient as possible.

Release Statement This article is reproduced at: https://dev.to/jelena_petkovic/razumevanje-renderovanja-i-rerenderovanja-u-react-aplikacijama-kako-funkcionisu-i-kako-ih-optimizovati-40cj?1 If there is any infringement, please contact study_golang @163.comdelete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3