Skip to main content

Basic React Usage

Create a new global state and export it, you can use with type and initial values

// user-state.ts

import State from "crown-state";

// State Type
export type UserType = {
age: number;
name: string;
};

export const $user = new State<UserType>({
age: 27,
name: "Selçuk",
});

Import state and start using it after attaching

// user-page.tsx

import State, { Attachment } from "crown-state";
import { useEffect, useState } from "react";
import { $user, UserType } from "../user-state";

export function UserPage() {
const [$userState, setUser] = useState<UserType>();

useEffect(() => {
// attach the user state and begin listen to changes
const att: Attachment = $user.attach((value, previousValue) => {
setUser(value);
});

return () => {
// detach and stop listening for changes
att.detach();
};
}, []);

return <div>{$userState?.name}</div>;
}

React demo