usePick
Selective field subscription with automatic performance optimization
Why Use usePick?
Perfect for performance optimization - only re-renders when the specific fields you're using actually change.
Performance Comparison
const userStore = createStore({
name: "John",
age: 30,
email: "john@example.com",
avatar: "avatar.jpg",
preferences: { theme: "dark", language: "en" },
lastLogin: new Date(),
});
// ❌ Inefficient: Re-renders on ANY store change
function UserName() {
const user = useStoreValue(userStore);
return <h1>{user.name}</h1>; // Only uses name, but subscribes to everything
}
// ✅ Efficient: Only re-renders when name changes
function OptimizedUserName() {
const { name } = usePick(userStore, "name");
return <h1>{name}</h1>; // Perfect - minimal subscriptions
}
API Reference
Syntax
const selectedFields = usePick(store, ...keys);
const selectedFields = usePickDeeply(store, ...keys); // Deep equality checking
Parameters
store
: ZenBox store instance...keys
: Field names to pick from the store
Returns
Object containing only the selected fields from the store.
Examples
Single Field
function UserName() {
const { name } = usePick(userStore, "name");
return <h1>{name}</h1>;
}
Multiple Fields
function UserContact() {
const { name, email } = usePick(userStore, "name", "email");
return (
<div>
<h2>{name}</h2>
<p>Email: {email}</p>
</div>
);
}
Deep Equality Checking
For nested objects that need deep comparison:
const settingsStore = createStore({
theme: {
colors: { primary: "#blue", secondary: "#gray" },
fonts: { heading: "Arial", body: "Helvetica" },
},
notifications: {
email: true,
push: false,
},
});
function ThemeSettings() {
// Deep comparison for nested objects
const { theme } = usePickDeeply(settingsStore, "theme");
return (
<div
style={{
color: theme.colors.primary,
fontFamily: theme.fonts.heading,
}}
>
Current theme configuration
</div>
);
}
usePick vs useStoreValue
Approach | Code | Performance |
---|---|---|
usePick | usePick(store, "name", "email") | ✅ Optimal - specific fields only |
useStoreValue + pick | useStoreValue(store, { pick: ["name", "email"] }) | ✅ Same performance, more verbose |
useStoreValue | useStoreValue(store) | ❌ Re-renders on any change |
Best Practices
✅ Be specific with field selection
// ❌ Bad: Pick nothing (same as useStoreValue)
const { name } = usePick(userStore);
// ❌ Bad: Pick too many fields
const { name } = usePick(userStore, "name", "age", "email", "avatar");
// ✅ Good: Only pick what you need
const { name, status } = usePick(userStore, "name", "status");
✅ Group related fields together
// ❌ Bad: Too granular
const { name } = usePick(userStore, "name");
const { email } = usePick(userStore, "email");
const { age } = usePick(userStore, "age");
// ✅ Good: Group related fields
const { name, email, age } = usePick(userStore, "name", "email", "age");
Related Hooks
useStoreValue
- Full store subscriptionuseComputed
- Derived reactive valuesuseWatch
- Side effects without re-renders