API Generic
use()

use

The use method allows you to subscribe to a specific path in the store and automatically re-render the component when the value changes.

use<P extends Paths<T>>(path: P & string): PathValue<T, P>

Parameters

OptionTypeRequiredDescription
pathstringYesThe property path in the store. Can be nested using dot notation (e.g., 'user.profile.name').

Returns

PathValue<T, P>: The current value at the specified path.

Description

The use method is a React hook that subscribes to changes at the specified path in the store. It returns the current value and triggers a re-render of the component whenever the value at that path changes. This method should only be used within React components or custom hooks.

Example

import { createStore } from '@devlab/store';
import React from 'react';
 
type StoreStates = {
  user: {
    name: string;
    age: number;
    preferences: {
      theme: 'light' | 'dark';
    };
  };
}
 
const store = createStore<StoreStates>({
  initialData: {
    user: {
      name: 'John Doe',
      age: 30,
      preferences: {
        theme: 'light'
      }
    }
  }
});
 
function UserProfile() {
  const userName = store.use('user.name');
  const age = store.use('user.age');
  const theme = store.use('user.preferences.theme');
 
  return (
    <div>
      <p>Name: {userName}</p>
      <p>Age: {age}</p>
      <p>Theme: {theme}</p>
      <button onClick={() => store.set('user.age', age + 1)}>
        Increment Age
      </button>
      <button onClick={() => store.set('user.preferences.theme', theme === 'light' ? 'dark' : 'light')}>
        Toggle Theme
      </button>
    </div>
  );
}
 
function App() {
  return (
    <div>
      <h1>User Profile</h1>
      <UserProfile />
      <button onClick={() => store.set('user.name', 'Jane Doe')}>
        Change Name
      </button>
    </div>
  );
}

In this example, the UserProfile component uses the use method to subscribe to various paths in the store. Whenever any of these values change (either through the buttons in UserProfile or the button in App), the UserProfile component will automatically re-render with the updated values.

Notes

  • The use method is a custom React hook and follows the rules of hooks. It should only be called at the top level of your React function components or custom hooks.
  • Each call to use creates a separate subscription, so you can subscribe to multiple paths within the same component.
  • The component will only re-render if the value at the subscribed path actually changes.