この記事を作った動機
単に自分用に、zustand の使い方を今 (2025/9/9) わかっている範囲で、書き出してみるだけ。
環境
- Vite
- React
- TypeScript
- Tailwind CSS
- zustand
概要
まだ全然わかっていないが、私の今 (2025/9/9) イメージとしては、「zustand とは、react で言う状態変数の管理に関するライブラリの一つで、親 -> 子 コンポーネントという流れで状態変数を渡していく以外で、コンポーネント間の状態変数を共有、管理することができるもの。」という感じである。
使い方
import
import { create } from "zustand";
宣言例
type DatabaseState = {
websocket: WebSocket | null;
serverIP: string | null;
changeServer: (ip: string) => void;
closeConnection: () => void;
getWebsocket: () => WebSocket | null;
};
export const useDatabaseStore = create<DatabaseState>((set, get) => ({
// 変数の初期化
websocket: null,
serverIP: "ws://localhost:50097",
// 変数を操作する関数群
changeServer: (ip: string) => {
set({ serverIP: ip });
},
closeConnection: () => {
const ws = get().websocket;
ws?.close();
set({ websocket: null });
},
getWebsocket: () => get().websocket,
}));
データを呼び出し、利用する
export function Acompornent(){
// 他の hooks と同様にコンポーネントのコードの先頭あたりに書く必要がある。
const websocket = useDatabaseStore((s) => s.websocket);
console.log(websocket)
// 何かしらのコード
}
関数を呼び出す
export function Acompornent(){
// 他の hooks と同様にコンポーネントのコードの先頭あたりに書く必要がある。
const changeServer = useDatabaseStore((s) => s.changeServer)
changeServer("ws://localhost:88091")
// 何かしらのコード
}
関係ありそうな記事
参考にしたサイトとか
- Introduction - Zustand
https://zustand.docs.pmnd.rs/getting-started/introduction (2025年9月9日) - ChatGPT
https://chatgpt.com/ (2025年9月9日) - Rules of Hooks – React
https://react.dev/warnings/invalid-hook-call-warning (2025年9月10日) - javascript - Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks - Stack Overflow
https://stackoverflow.com/questions/53472795/uncaught-error-rendered-fewer-hooks-than-expected-this-may-be-caused-by-an-acc (2025年9月10日)