Blog>
Snippets

Implementing Lazy Loading of State

Present an example of how to implement lazy loading of state in TanStack Store to enhance performance in large-scale applications.
import { createStore, lazyLoad } from '@tanstack/store';

// Define the initial state
const initialState = {
  userDetails: null,
  posts: []
};

// Create the store
const appStore = createStore({
  initialState
});
This code snippet initializes the TanStack Store. It starts by importing createStore and lazyLoad from '@tanstack/store', then defines an initial state with userDetails set to null and an empty array for posts. Finally, it creates the store with the initial state.
const loadUserDetails = async () => {
  const userDetails = await fetch('/api/user').then(res => res.json());
  appStore.setState(prevState => ({
    ...prevState,
    userDetails
  }));
};
This code snippet defines an asynchronous function loadUserDetails that fetches user details from an API and updates the state of the appStore with the fetched userDetails.
const loadPosts = async () => {
  const posts = await fetch('/api/posts').then(res => res.json());
  appStore.setState(prevState => ({
    ...prevState,
    posts
  }));
};
This function, loadPosts, performs an asynchronous operation to fetch posts from an API and updates the appStore state with the new posts array.
export const useLazyLoadUserDetails = () => lazyLoad(appStore, loadUserDetails);

export const useLazyLoadPosts = () => lazyLoad(appStore, loadPosts);
Here, the lazyLoad function from TanStack Store is used to create two new functions, useLazyLoadUserDetails and useLazyLoadPosts. These functions, when called, lazily load userDetails and posts, respectively, by invoking the corresponding asynchronous loader functions. This optimizes performance by fetching state only when necessary.