Optimizing Performance by Preventing Unnecessary Re-renders
Use TanStack Router Devtools to identify components that re-render unnecessarily on route changes and apply memoization to optimize their performance.
import { memo } from 'react';
const MyComponent = memo(({ propA, propB }) => {
// Component code here
return <div>{propA} - {propB}</div>;
});
export default MyComponent;
This code snippet wraps a React component with memo, which is a higher order component provided by React. memo performs a shallow comparison of the component's props and prevents the component from re-rendering if the props haven't changed. This is particularly useful for optimizing the performance of components that re-render unnecessarily during route changes with TanStack Router.
import { useMemo } from 'react';
const MyComponent = ({ list }) => {
const sortedList = useMemo(() => list.sort(), [list]);
return (
<ul>{sortedList.map(item => <li key={item}>{item}</li>)}</ul>
);
};
export default MyComponent;
This snippet demonstrates the use of useMemo for expensive calculations, like sorting a list. useMemo will only recompute the sorted list when the list prop changes, thus avoiding unnecessary recalculations and re-renders. This technique enhances performance, especially when navigating between routes that do not alter the list but cause the component to re-render.
import { useEffect } from 'react';
import { useLocation } from '@tanstack/react-router';
const RouteEffect = () => {
const location = useLocation();
useEffect(() => {
// Effect that runs only when the route changes
console.log('Route changed to: ', location.pathname);
}, [location]);
return null;
};
export default RouteEffect;
Here we make use of useLocation hook from TanStack Router along with useEffect from React. The useEffect hook's dependency array includes location, which comes from useLocation. This setup ensures that the effect inside useEffect runs only when the route changes. This can be used to trigger performance optimizations or updates based on route changes without causing unnecessary re-renders to the component hierarchy.