Global State
In any ReactJS
app having a global state is essential to control
a specific state without prop drilling
or using context
We are using Zustand
for our global state as it offers a really clean and easy to use API
There are two stores for our global state
-
Main store
- Includes more of the logic controlling state
- The global state is located under
/src/store/index.ts
-
UI store
- Includes more of the ui controlling state
- The UI state is located under
/src/store/ui.ts
Usage
You can use both in any client component or client page
/src/app/example/page.tsx
"use client";
import { useAppState } from "store";
import { useUIState } from "store/ui";
const ExamplePage = () => {
const user = useAppState((state) => state.user);
const authDialogOpen = useUIState((state) => state.authDialogOpen);
const setAuthDialogOpen = useUIState((state) => state.setAuthDialogOpen);
return <div>ExamplePage</div>;
};
export default ExamplePage;
Note
Make sure to use only specific keys useAppState((state) => state.user)
not the whole state useAppState((state) => state)
unless there is a good reason for it, to not re-render the component unnecessarily.
Adding more to the store
Let's say you want to add more properties to the store
- Navigate to
/src/store/index.ts
- Add your new properties
/src/store/index.ts
type AppState = {
// ...
// define the types your new state
// one for accessing and one for setting (similar to useState)
myScore: number;
setMyScore: (value: number) => void;
};
export const useAppState = create<AppState>((set, get) => ({
// add the new properties by assign their default values
myScore: 10,
// use the set method provided by the create function to set the new value
setMyScore: (myScore) => set({ myScore }),
}));
- Use your global state new properties this way
/src/app/example/page.tsx
"use client";
import { useUIState } from "store/ui";
const ExamplePage = () => {
const myScore = useAppState((state) => state.myScore);
const setMyScore = useAppState((state) => state.setMyScore);
return <div>ExamplePage</div>;
};
export default ExamplePage;
🎉 That's it!