Implementing Selective Subscriptions in TanStack Store
Demonstrate how to use selective subscriptions in TanStack Store to only re-render components when specific parts of the state change.
import { useStoreState } from 'easy-peasy'; // Importing necessary hook from TanStack Store
This line imports the useStoreState hook from TanStack Store, which is essential for selecting specific slices of state.
const selectUserProfile = state => state.user.profile; // Defining a selector for user's profile
Here, a selector function is defined that takes the entire state and returns only the part of the state concerning the user's profile.
const UserProfileComponent = () => {
const userProfile = useStoreState(selectUserProfile);
// Using the selector with useStoreState hook
return (
<div>
<h1>User Profile</h1>
<p>Name: {userProfile.name}</p>
<p>Email: {userProfile.email}</p>
</div>
);
};
This component utilizes the useStoreState hook with the previously defined selector to subscribe only to the user profile slice of the state. It only re-renders when the user profile state changes.