You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Use React dev tools "Highlight Updates" to see what's re-rendering. Then be strategic.
Ask: why is this component re-rendering?
Ask: Could I avoid passing the prop that's causing it to re-render? Could it access this data via Context instead to avoid passing it through intermediate components that don't need it?
Use console.time like this, against the prod build, to measure slowness and compare to a before and after to determine if useMemo is a net win: console.time('filter array'); const visibleTodos = getFilteredTodos(todos, filter); console.timeEnd('filter array');
functionExpensiveTree(){letnow=performance.now();while(performance.now()-now<100){// Artificial delay -- do nothing for 100ms}return<p>I am a very slow component tree.</p>;}
Statically render if possible (Easy via Next.js, Gatsby)
Lift fetches to common parent or fetch in parallel via tools consider server rendering to avoid slow network waterfalls (easy via Remix / Next.js)
Prefetch / render-as-you-fetch (React's "default" is fetch as you render since the render triggers a fetch via useEffect). React-query's prefetching is a simple way to render as you fetch. Remix also does this by default since nested routes declare data dependencies and run in parallel on the server. My tweet on this
Consider using million's block virtual DOM instead if there is a lot of static content with little dynamic content. Million diffs state instead of DOM, which is fast if there's a little state, but a LOT of DOM.
Context
Minimize context usage - Consider component composition instead (composing components that accept children, so props "Lifted" / composed at a higher level in the tree). Dan calls this lift content up.
Assure keys are assigned, and stable over time. Their values should not change based on array order or edits to the data.
Reuse keys to avoid needless renders for items that frequently appear/disappear in the viewport.
Consider using the array’s index as key for dynamic lists with stateless items, where items are replaced with the new ones - paginated lists, search and autocomplete results and the like. This will improve the list’s performance because the entire thing doesn't have to re-render. The component instances are reused. Demo and blog post
State
Keep state as local as possible. Start by declaring state in the component that uses it. Lift as needed.
Store data that doesn't need to render in refs
Consider useReducer over useState so you can pass dispatch down instead of callbacks (avoids needless renders)
Avoid deep cloning. To avoid, only clone the subobjects that have changed. Or perhaps better yet, avoid nesting objects in state since doing so can lead to needless renders. Instead, "flatten" state by creating separate pieces of state.
Pass the minimal amount of data to each component (remember, components re-render when props change)
Pass primitives (strings, numbers...) to child components to assist with diffing. Avoid passing arrow funcs and objects on props when performance is a concern since it leads to needless re-renders of child components.
useDeferredValue if it's a low priority update and you can't use useTransition because you don't control the value coming in (coming from third party or via a prop you can't control). Another demo
Component composition / Children
Put content that renders frequently in a separate component to minimize the amount that's rendered
Embrace reusable components. Each reuse of a reusable component is nearly free.
Compose higher level components out of lower level components.
Create layout components to centralize reusable layout
Declare functions that need not be in the React component outside the component. This way they're not reallocated on every render.
Declare static values outside the component so they're not reallocated on every render.
Design
Use pagination, sorting, filtering, pages, tabs, accordions, modals, etc to avoid displaying too much data at the same time.
Use tools like react-window to handle large lists by only rendering what's currently visible.
Consider implementing optimistic updates when the API is slow (immediately update the UI even though the API call is still in progress behind the scenes)
Bundle optimization
Split the bundle via React.lazy or use loadable-components. Not merely pages. Consider splitting components too. Remember that Next.js automatically bundle splits. When lazy loading in React Router, put the loader in a different file than the lazy loaded component, or the bundle split won't work.
Check what's in your bundle via webpack-bundle-analyzer
Third party libraries
Avoid named imports when importing third party libraries / components (doing so can bloat the bundle by importing the entire lib) For example, avoid import { Tab } from "x". Prefer import Tab from "x/Tab" when possible.
Prefer native HTML inputs over fancy components that simulate native behaviors
Use Partytown to load heavy third party libraries via a separate web worker thread
Styling
Consider Tailwind to minimize style bundle size
Consider CSS modules over CSS-in-JS to avoid a runtime
Framework
Consider Gatsby or Astrobuild to compile components into static HTML
42+ ways to make your React app faster ⚛️:
Performance Testing
console.time
like this, against the prod build, to measure slowness and compare to a before and after to determine ifuseMemo
is a net win:console.time('filter array'); const visibleTodos = getFilteredTodos(todos, filter); console.timeEnd('filter array');
Generate a simple fake dataset in a loop.
Generate a large fake dataset using tools like Faker, Chance, etc.
Simulate a slow component via a loop:
Forms
HTTP
Rendering
useEffect
). React-query's prefetching is a simple way to render as you fetch. Remix also does this by default since nested routes declare data dependencies and run in parallel on the server. My tweet on thisContext
Routing
Keys
key
for dynamic lists with stateless items, where items are replaced with the new ones - paginated lists, search and autocomplete results and the like. This will improve the list’s performance because the entire thing doesn't have to re-render. The component instances are reused. Demo and blog postState
useTransition
for low priority updates (reduces jank) - DemouseLayoutEffect
to avoid a Flash of unstyled content when you need to read and manipulate the DOM before the user sees it - DemoMemoization / Identity
Props
useTransition
because you don't control the value coming in (coming from third party or via a prop you can't control). Another demoComponent composition / Children
children
don’t re-render since they are just props. Note: don't pass a function as a child, since it'll still re-render because the func will be recreated on each renderDesign
Bundle optimization
Third party libraries
import { Tab } from "x"
. Preferimport Tab from "x/Tab"
when possible.Styling
Framework
More examples
https://piyushsinha.tech/optimizing-performance-in-react-apps-i
https://piyushsinha.tech/optimizing-performance-in-react-apps-ii
The text was updated successfully, but these errors were encountered: