Blog>
Snippets

Implementing State Management with TanStack Ranger

Demonstrate how to use TanStack Ranger for managing application state, focusing on a simple user authentication flow.
import { createRanger } from 'tanstack-ranger';

// Define the initial state
const initialState = {
  isAuthenticated: false,
  user: null
};

// Create a ranger for state management
export const userRanger = createRanger({
  initialState
});
This piece of code imports the createRanger function from the 'tanstack-ranger' library and uses it to create a new state management ranger for user authentication. We define an initial state with two properties: isAuthenticated and user, then pass this state to createRanger to create our userRanger.
// Action to log in a user
export const loginUser = (userRanger, user) => {
  userRanger.setState({
    isAuthenticated: true,
    user
  });
};

// Action to log out a user
export const logoutUser = (userRanger) => {
  userRanger.setState({
    isAuthenticated: false,
    user: null
  });
};
Here, we define two actions: loginUser and logoutUser. loginUser accepts the userRanger and a user object, and it sets the state's isAuthenticated to true and updates the user. logoutUser sets isAuthenticated to false and resets the user to null.
// Usage example
import { userRanger, loginUser, logoutUser } from './userState';

// Simulate log in
loginUser(userRanger, { name: 'John Doe', email: 'john@example.com' });

// Access the updated state
console.log(userRanger.getState());

// Simulate log out
logoutUser(userRanger);

// Access the state after logout
console.log(userRanger.getState());
In this usage example, we import the userRanger and action creators from the 'userState' module. We simulate a user log in by calling loginUser with a sample user object. We then access the updated state using userRanger.getState() to see the changes. Lastly, we simulate a user log out by calling logoutUser and access the state again to see it reset.