Skip to content

Commit 3cdda77

Browse files
committed
add context
1 parent f9a109e commit 3cdda77

File tree

4 files changed

+48
-3
lines changed

4 files changed

+48
-3
lines changed

Diff for: compat/README.md

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# fre/compat
2+
3+
> Something that can be implemanted in userland.
4+

Diff for: compat/context.ts

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import {
2+
useReducer,
3+
useLayout,
4+
useRef,
5+
} from 'fre'
6+
7+
export const createContext = defaultValue => {
8+
const context = {
9+
value: defaultValue,
10+
subs: new Set(),
11+
Provider: function Provider({ value, children }) {
12+
useLayout(() => {
13+
context.subs.forEach((fn:Function) => fn(value))
14+
context.value = value
15+
})
16+
return children
17+
}
18+
}
19+
return context
20+
}
21+
22+
export const useContext = (context, selector) => {
23+
const subs = context.subs
24+
const [, forceUpdate] = useReducer(c => c + 1, 0)
25+
const selected = selector ? selector(context.value) : context.value
26+
const ref = useRef(null)
27+
useLayout(() => {
28+
ref.current = selected
29+
})
30+
useLayout(() => {
31+
const fn = nextValue => {
32+
if (ref.current === selector(nextValue)) return
33+
forceUpdate()
34+
}
35+
subs.add(fn)
36+
return () => subs.delete(fn)
37+
}, [subs])
38+
return selected
39+
}
40+

Diff for: compat/index.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1-
import { lazy, Suspense } from './Suspense'
1+
import { lazy, Suspense } from './suspense'
2+
import { createContext, useContext } from './context'
23

3-
export { lazy, Suspense }
4+
export { lazy, Suspense, createContext, useContext }

Diff for: tsconfig.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,5 @@
1111
"sourceMap": false
1212
},
1313
"exclude": ["node_modules", "dist"],
14-
"include": ["src", "compat/Suspense.ts"]
14+
"include": ["src", "compat/suspense.ts"]
1515
}

0 commit comments

Comments
 (0)