Blog>
Snippets

Optimizing React Components using Selective State Management

Illustrate the use of selective state management in TanStack Ranger to prevent unnecessary re-renders in a React application, thus optimizing performance.
import { useRanger } from 'tanstack-ranger-react';
Import the useRanger hook from the tanstack-ranger-react library to manage state selectively.
const MyComponent = () => {
  // Use useRanger hook to access and control the state
  const { state, setState } = useRanger({
    initialRange: { start: 0, end: 10 }
  });
Initialize MyComponent and useRanger with initialRange state. The state includes a range with a start and end value.
  // Function to update the range selectively
  const updateRangeStart = (newStart) => {
    setState(prev => ({ ...prev, start: newStart }));
  };
Define a function (updateRangeStart) to update only the start value of the range, showcasing selective state management.
  // Function to update the range end selectively
  const updateRangeEnd = (newEnd) => {
    setState(prev => ({ ...prev, end: newEnd }));
  };
Define a function (updateRangeEnd) to update only the end value of the range, thereby avoiding unnecessary re-renders for components depending only on other parts of the state.
  return (
    <div>
      <p>Current Range: {state.start} - {state.end}</p>
      <button onClick={() => updateRangeStart(state.start + 1)}>Increase Start</button>
      <button onClick={() => updateRangeEnd(state.end + 1)}>Increase End</button>
    </div>
  );
};
Render the component displaying the current range and providing buttons to update the start and end of the range individually.
export default MyComponent;
Export MyComponent to be used in other parts of the application.