Last active
November 13, 2023 01:40
-
-
Save ynifamily3/d243af92d00bcc756e1ae46115cd1c48 to your computer and use it in GitHub Desktop.
전역 상태관리 예제 (useSyncExternalStore)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client"; | |
import { todosStore } from "@/store/todoStore"; | |
import { useSyncExternalStore } from "react"; | |
export default function AAA() { | |
const todos = useSyncExternalStore( | |
todosStore.subscribe, | |
todosStore.getSnapshot | |
); | |
return ( | |
<main className="p-24 bg-white"> | |
useSyncExternalStore 테스트 | |
<br /> | |
<button onClick={() => todosStore.addTodo("집에가기: " + Math.random())}> | |
할 일 추가 | |
</button> | |
<hr /> | |
<ul> | |
{todos.map((todo) => ( | |
<li key={todo.id}>{todo.text}</li> | |
))} | |
</ul> | |
</main> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Listener = () => void; | |
let nextId = 0; | |
let todos = [{ id: nextId++, text: "Todo #1" }]; | |
let listeners: Array<Listener> = []; // 또는 new Set() | |
export const todosStore = { | |
addTodo(text: string) { | |
todos = [...todos, { id: nextId++, text }]; | |
emitChange(); | |
}, | |
subscribe(listener: Listener) { | |
console.log("구독 좋아요", listener); | |
listeners = [...listeners, listener]; // 또는 listeners.add(...) | |
// 되돌리기 수행하는 프로시져 반환 | |
return () => { | |
console.log("구독 되돌리기", listener); | |
listeners = listeners.filter((l) => l !== listener); // 또는 listeners.delete(...) | |
}; | |
}, | |
getSnapshot() { | |
return todos; | |
}, | |
}; | |
function emitChange() { | |
for (const listener of listeners) { | |
console.log("리스너가 뭔데", listener); | |
listener.call(null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment