Blog>
Snippets

Extending TanStack Store with Custom Hooks for Reusability

Illustrate how to create custom hooks in TanStack Store for common state-related logic, enhancing modularity and reusability across components.
import { useStoreActions, useStoreState } from 'react-tanstack';

// Custom hook to get and increment counter
export function useCounter() {
  const counter = useStoreState(state => state.counter);
  const increment = useStoreActions(actions => actions.increment);

  return { counter, increment };
}
This custom hook, `useCounter`, encapsulates the logic for accessing and modifying the `counter` state. It uses the `useStoreState` hook to retrieve the current value of `counter` and `useStoreActions` to get the `increment` action. This abstraction promotes reusability and modularity by allowing any component to easily interact with the counter state through a single hook.
import { useStoreActions } from 'react-tanstack';

// Custom hook to manage user login
export function useLogin() {
  const login = useStoreActions(actions => actions.login);

  const performLogin = async (username, password) => {
    // Placeholder for authentication logic
    const isSuccess = await authenticate(username, password);
    if (isSuccess) {
      login({ username });
    }
  };

  return { performLogin };
}
This custom hook, `useLogin`, abstracts the authentication logic, encapsulating the store action to log a user in. It leverages `useStoreActions` to get the `login` action and defines a `performLogin` function that simulates an authentication process. This function can be easily reused across different components that require user authentication.