Skip to main content

With Custom React Hook

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",
});

Add a custom hook

// useGlobalState.ts

import State, { Attachment } from 'crown-state'
import { useEffect, useState } from 'react'

export function useGlobalState<T>(globalState: State<T>) {
const [state, setState] = useState<T>(globalState.value);

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

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

return state;
}

Just import custom hook and state

// user-page.tsx

import { $user, UserType } from "../user-state";
import { useGlobalState } from "../hooks";

export function UserPage() {
// automatic detach and attach operations are done with custom hook
const $userState = useGlobalState<UserType>($user);

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

Advance demo