Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created March 8, 2020 00:47
Show Gist options
  • Select an option

  • Save itsMapleLeaf/4e7faddb68eac26734919de53e64bf74 to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/4e7faddb68eac26734919de53e64bf74 to your computer and use it in GitHub Desktop.
state atom
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