Blog>
Snippets

Creating Custom Hooks for State Management

Demonstrate the creation of custom hooks that utilize TanStack Store for accessing and manipulating application state, ensuring components can easily interact with the global state.
import { useStore } from 'react-tanstack-store';
First, import the useStore hook from the react-tanstack-store library.
const useCounter = () => {
  const [state, actions] = useStore(state => state.counter);
  return {
    count: state.count,
    increment: () => actions.setState({ count: state.count + 1 }),
    decrement: () => actions.setState({ count: state.count - 1 })
  };
};
Then, create a custom hook named useCounter. This hook uses the useStore hook to access the counter's state from the global store and returns an object that includes the count state, an increment function, and a decrement function. The increment and decrement functions update the count state.
const App = () => {
  const { count, increment, decrement } = useCounter();
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
};
Finally, use the custom useCounter hook within a React functional component called App. This component utilizes the hook to display the current count and render buttons that call the increment and decrement functions when clicked.