Blog>
Snippets

Handling Global State Management in TanStack Ranger

Show how to integrate a global state management solution, like Redux or Context API, with TanStack Ranger components for complex state handling scenarios.
import React, { createContext, useContext, useReducer } from 'react';
import { useRanger } from 'react-ranger';

const SliderStateContext = createContext();
const SliderDispatchContext = createContext();
Setting up a context for global state management and a context for dispatching actions to that state.
function sliderReducer(state, action) {
  switch (action.type) {
    case 'update':
      return { ...state, values: action.payload };
    default:
      throw new Error(`Unhandled action type: ${action.type}`);
  }
}
Defining a reducer function to handle state changes based on dispatched actions.
function SliderProvider({ children }) {
  const [state, dispatch] = useReducer(sliderReducer, { values: [10, 50] });
  return (
    <SliderStateContext.Provider value={state}>
      <SliderDispatchContext.Provider value={dispatch}>
        {children}
      </SliderDispatchContext.Provider>
    </SliderStateContext.Provider>
  );
}
Creating a Provider component to wrap the part of the app that needs access to the slider values state and dispatch functions.
function useSliderState() {
  const context = useContext(SliderStateContext);
  if (context === undefined) {
    throw new Error('useSliderState must be used within a SliderProvider');
  }
  return context;
}
Creating a custom hook to provide easy access to the slider state context throughout the app.
function useSliderDispatch() {
  const context = useContext(SliderDispatchContext);
  if (context === undefined) {
    throw new Error('useSliderDispatch must be used within a SliderProvider');
  }
  return context;
}
Creating a custom hook to provide easy access to the slider dispatch context throughout the app.
function RangeSlider() {
  const dispatch = useSliderDispatch();
  const { getTrackProps, handles } = useRanger({
    values: useSliderState().values,
    onChange: (values) => dispatch({ type: 'update', payload: values }),
    onDrag: (values) => dispatch({ type: 'update', payload: values }),
    min: 0,
    max: 100,
    stepSize: 1
  });
  return (
    <div {...getTrackProps()}>
      {handles.map(({ getHandleProps }) => (
        <button {...getHandleProps()}></button>
      ))}
    </div>
  );
}
Integrating TanStack Ranger with the global state management set up to control the slider values.