Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-render a heavy React component with a low priority?

Tags:

reactjs

With some parameters, I have a React component that can take a few seconds to render but it is not a problem at all if it is not up-to-date.

To prevent the UI from being frozen, I would like to render it only when the user is not changing the form parameters.

It could be a defer, debounce, or another way of doing that. How would you achieve that? Thank you!

like image 853
Alexis Delrieu Avatar asked Feb 09 '26 18:02

Alexis Delrieu


2 Answers

React 18

With React 18, a new API has been released that lets you mark state updates as less-important transition updates (as opposed to normal updates using useState/useReducer, which are now considered urgent updates).

Here's an example:

import {startTransition} from 'react';

// Urgent: Show what was typed
setInputValue(input);

// Mark any state updates inside as transitions
startTransition(() => {
  // Transition: Show the results
  setSearchQuery(input);
});

See https://reactjs.org/blog/2022/03/29/react-v18.html#new-feature-transitions

Another super helpful post with a real world example: https://github.com/reactwg/react-18/discussions/65

like image 182
merlindru Avatar answered Feb 12 '26 14:02

merlindru


You can use React.lazy and Suspense to load the component on demand.

Here I use a flag loadExtra to know when to load the extra component, offering a button to load it sooner than the 20 seconds the timeout is set for.

Edit new-dust-066uz

import { ..., lazy, Suspense } from "react";

const ExtraComponent = lazy(() => import("./ExtraComponent"));

const App = () => {
  const [loadExtra, setLoadExtra] = useState(false);

  ...
  <Suspense fallback="Loading...">
    <ExtraComponent />
  </Suspense>;
  ...
};

export default App;

I know of this trick, to force a Component re-render. By passing the key prop to the Component, when the key changes, the component will be forced to re-render

So whenever you deem the user is not changing the form, you can change the key and the React Component will be re-rendered.

like image 43
a.mola Avatar answered Feb 12 '26 14:02

a.mola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!