Skip to content

Introduction

valdres-react builds on the vanilla js valdres package and adds various hooks and the optional <Provider />.

Quick Start

Install

npm
npm install valdres-react

Create atoms and selectors

An atom contains a piece of state while a selector represents aggregated state or slices of state based on one or more atoms. atomFamily and selectorFamily are used when you have collections of similar objects that vary based on input paramters like an id or filters.

In the example below we have the folling state:

  • currentUserIdAtom an atom that fetches and stores the currents user id
  • userAtom a atomFamily that stores user objects by userId
  • userDisplayNameSelector a selectorFamily that generates a display name based on the userAtom family
currentUserIdAtom.ts
import { faker } from "@faker-js/faker"
import { atom } from "valdres-react"
 
const fetchCurrentUserId = () => faker.string.uuid()
 
export const currentUserIdAtom = atom(fetchCurrentUserId)

Use the atoms and selectors in React

Once we have our atoms and selectors we can subscribe to them in our React components.

UserProfile.tsx
import { useValue } from "valdres-react"
import { userDisplayNameSelector } from "./state/selectors/userDisplayNameSelector"
import { UserAvatar } from "./UserAvatar"
 
export function UserProfile({ userId }: { userId: string }) {
    const displayName = useValue(userDisplayNameSelector(userId))
    return (
        <div
            style={{
                display: "flex",
                alignItems: "center",
                height: "40px",
                width: "fit-content",
                border: "0.5px solid gray",
                padding: "8px 12px",
                borderRadius: "5px",
            }}
        >
            <UserAvatar userId={userId} />
            <span style={{ marginLeft: "8px" }}>{displayName}</span>
        </div>
    )
}

Provider mode (optional)

Unless you wrap your app in a <Provider> the default global store is used. This is totaly fine. You can access the default store outside the react tree with getDefaultStore() from the valdres-react package.

If you want more control or segregate your state across multiple stores you can wrap any part of the React tree with a <Provider>. The Provider by default creates a new store unless you provide your own store created using the store() function.

App.tsx
import { Provider } from "valdres-react"
import { store } from "./store"
 
export function App = ({ children }) {
    return <Provider store={store}>
        {children}
    <Provider>
}