Blog>
Snippets

Creating Custom Hooks with TanStack Ranger

Show how to create custom hooks in TanStack Ranger for managing local component state, focusing on a specific example like a toggle component.
import { useState, useCallback } from 'react';
import { useRanger } from 'react-ranger';
Import the necessary hooks from React and the useRanger hook from react-ranger.
function useToggleRanger({ initialValues = [0, 100] }) {
  const [values, setValues] = useState(initialValues);
  const { getTrackProps, handles } = useRanger({
    min: 0,
    max: 100,
    stepSize: 1,
    values,
    onChange: setValues
  });

  const toggle = useCallback(() => {
    setValues((currentValues) =>
      currentValues[0] > 0 ? [0, currentValues[1]] : [100, currentValues[1]]
    );
  }, []);

  return { values, setValues, getTrackProps, handles, toggle };
}
Create a custom hook named useToggleRanger that manages a toggle functionality on top of the range slider. It initializes with values and provides a toggle method to switch the first value between 0 and 100, effectively toggling the range.
export default useToggleRanger;
Exports the custom hook so it can be used in other components.