Blog>
Snippets

Optimizing React Components with TanStack Ranger Caching

Provide an example of using TanStack Ranger caching to memoize expensive operations and reduce re-renders in a React application.
import { useRanger } from 'tanstack-ranger-react';

const expensiveOperation = (number) => {
  // Simulating an expensive operation
  console.log('Expensive operation running');
  return number * number;
};
First, we import useRanger from 'tanstack-ranger-react' to use caching capabilities of TanStack Ranger. We define an expensive operation that we want to memoize to prevent unnecessary re-executions.
const MyComponent = ({ number }) => {
  const result = useRanger(() => expensiveOperation(number), [number]);

  return (
    <div>
      Result: {result}
    </div>
  );
};
In the MyComponent, we use useRanger hook to cache the result of the expensiveOperation. The operation is only re-executed if the 'number' prop changes, thanks to the dependency list provided to useRanger, reducing unnecessary re-renders and optimizing performance.
export default MyComponent;
Finally, we export MyComponent so it can be used in other parts of the application. The use of TanStack Ranger's caching mechanism helps in optimizing the React component by reducing the need for re-calculating expensive operations.