useStoreValue / useComputed

Subscribe to stores and create computed values for reactive components

useStoreValue

useStoreValue is a React hook that allows you to read the state of a store.

It's similar to store.value but it will trigger the component re-render when the state changes.

So you can use it to keep the component state in sync with the store.

// ✅ Component re-renders when store changes
function Counter() {
  const { count } = useStoreValue(counterStore);
  return <div>Current Count: {count}</div>;
}

// ❌ Component shows initial value only, no reactivity
function StaticCounter() {
  const count = counterStore.value.count;
  return <div>Static Count: {count}</div>;
}

usePick

If the component only needs a few fields from the store, you can use pick to select specific fields.

So the component will only re-render when the selected fields change.

const { name, followers } = useStoreValue(userStore, {
  pick: ["name", "followers"],
});

Or use usePick to select specific fields, which is a shortcut for useStoreValue(store, { pick }).

const { name, followers } = usePick(userStore, "name", "followers");

useComputed

The useComputed hook is similar to useStoreValue, but it will re-compute the value when the state changes.

And it will trigger the component re-render only when the computed value changes.

Similar to the computed in Vue.

Single Store Computation

const counterStore = createStore({ count: 0 });

function Counter() {
  const isEven = useComputed(() => counterStore.value.count % 2 === 0);

  return <div>Is Even: {isEven ? "Yes" : "No"}</div>;
}

counterStore.setState({ count: 1 }); // ✅ Re-renders (even → odd)
counterStore.setState({ count: 3 }); // ❌ No re-render (still odd)

Multi-Store Computation

Seamlessly combine data from multiple stores:

const store1 = createStore({ count: 1 });
const store2 = createStore({ isEven: true });

const value = useComputed(() => {
  return store1.value.count + (store2.value.isEven ? 1 : 0);
});