Implementing Lazy Loading with TanStack Store
Illustrate how to implement lazy loading of state data in a React component using TanStack Store, improving initial load performance.
import { useState } from 'react';
import { useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
First, import useState from React for local state management, and import useAtom and atomWithStorage from jotai for state management with TanStack Store (formerly jotai).
const lazyDataAtom = atomWithStorage('lazyData', null);
Define an atom with persistent storage that initially has a null value. This atom will asynchronously load data when required.
const fetchDataAsync = async () => {
// simulate fetching data
return new Promise((resolve) => setTimeout(() => resolve('Fetched Data'), 2000));
};
Create an async function that simulates fetching data from an API with a delay, to mimic network request latency.
function LazyLoadedComponent() {
const [data, setData] = useAtom(lazyDataAtom);
const [isLoading, setIsLoading] = useState(false);
async function loadData() {
if (data !== null) return; // Data already loaded
setIsLoading(true);
const fetchedData = await fetchDataAsync();
setData(fetchedData);
setIsLoading(false);
}
return (
<div>
<button onClick={loadData}>{isLoading ? 'Loading...' : 'Load Data'}</button>
{data && <p>{data}</p>}
</div>
);
}
This component utilizes the defined atom to manage the state of the lazy-loaded data. It includes a button to trigger the data fetching and displays the data once loaded. The component checks if data is already loaded to prevent unnecessary fetches.