Created
March 8, 2020 00:47
-
-
Save itsMapleLeaf/4e7faddb68eac26734919de53e64bf74 to your computer and use it in GitHub Desktop.
state atom
This file contains hidden or 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
| import { useEffect, useState } from "react" | |
| export type Atom<T> = { | |
| set(newValue: T): void | |
| get(): T | |
| listen(listener: (value: T) => void): () => void | |
| } | |
| export function createAtom<T>(initialValue: T): Atom<T> { | |
| let currentValue = initialValue | |
| const listeners = new Set<(value: T) => void>() | |
| return { | |
| set(newValue: T) { | |
| currentValue = newValue | |
| listeners.forEach((l) => l(newValue)) | |
| }, | |
| get() { | |
| return currentValue | |
| }, | |
| listen(listener: (value: T) => void) { | |
| listeners.add(listener) | |
| return () => { | |
| listeners.delete(listener) | |
| } | |
| }, | |
| } | |
| } | |
| export function useAtom<T>(atom: Atom<T>) { | |
| const [value, setValue] = useState(atom.get()) | |
| useEffect(() => atom.listen(setValue), [atom]) | |
| return value | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment