Creating a Custom Hook with TanStack Ranger Core
Demonstrate how to create a custom hook that leverages TanStack Ranger Core for state management in a React component.
import { useRanger } from 'tanstack-ranger-core';
Import the useRanger hook from the 'tanstack-ranger-core' package.
function useCustomPicker() {
// Setup initial state using the useRanger hook
const [state, setState] = useRanger({
initialValue: 10
});
// Function to increment the value
const increment = () => setState(state + 1);
// Function to decrement the value
const decrement = () => setState(state - 1);
// Expose the state and control functions to the component
return { state, increment, decrement };
}
Create a custom hook named useCustomPicker that utilizes the useRanger hook for state management. It initializes the state, provides functions to increment and decrement the value, and returns the state and functions.
function MyComponent() {
// Use the custom hook inside a component
const { state, increment, decrement } = useCustomPicker();
return (
<div>
<p>Value: {state}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
}
Demonstrate how the custom hook (useCustomPicker) can be utilized within a React component (MyComponent) to manage state with increment and decrement functionality.