Blog>
Snippets

Optimizing Component Renders with Selective State Subscription

Provide a code example showing how to use the `useStoreState` hook to subscribe to specific parts of the state, minimizing unnecessary re-renders by only updating components when relevant state slices change.
import { useStoreState } from 'easy-peasy'; // Importing useStoreState hook from easy-peasy
First, import the useStoreState hook from your state management library, assuming easy-peasy is being used in this example.
const MyComponent = () => {
  const userName = useStoreState(state => state.user.name); // Subscribing to only the user's name part of the state
}
In your component, use the useStoreState hook to subscribe to specific parts of the state. Here, we subscribe only to the user's name.
// Assuming that the state shape is
// { user: { name: 'John', age: 30 }, products: [...]}
This comment describes the shape of the state for clarity. It's not actual code but gives context to the useStoreState hook usage.
return (<div>Hello, {userName}</div>);
Render part of the component, which shows the usage of the subscribed state. This component will re-render only if the `userName` changes.