Optimizing Re-renders in TanStack Ranger
Provide an example of using React.memo or useCallback in the context of a TanStack Ranger component to optimize performance and prevent unnecessary re-renders.
import React, { useCallback } from 'react';
import { useRanger } from 'react-ranger';
Imports necessary hooks from React and the useRanger hook from react-ranger.
const RangeSlider = React.memo(({ min, max, step, values, onDrag }) => {
const { getTrackProps, handles } = useRanger({
min,
max,
step,
values,
onDrag
});
return (
<div {...getTrackProps({
style: {
height: '4px',
background: 'grey',
boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.3)',
borderRadius: '2px'
}
})}>
{handles.map(({ getHandleProps }) => (
<button {...getHandleProps()} />
))}
</div>
);
});
Defines a RangeSlider component using React.memo for optimizing performance by memorizing props and re-rendering only when props change.
const ParentComponent = () => {
const handleDrag = useCallback((values) => {
console.log(values);
}, []);
return (
<RangeSlider
min={0}
max={100}
step={1}
values={[10, 90]}
onDrag={handleDrag}
/>
);
};
Defines a ParentComponent, using the RangeSlider with a memorized callback handleDrag via useCallback to avoid unnecessary re-renders.