-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample.partial-context.heavy.tsx
More file actions
59 lines (50 loc) · 1.84 KB
/
Copy pathexample.partial-context.heavy.tsx
File metadata and controls
59 lines (50 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { memo, useCallback, useMemo } from "react";
import { createPartialContext } from "..";
import type { ExampleStore } from "./example";
const StoreCtx = createPartialContext<ExampleStore>();
type PartialResult = {
value: number;
prevValue: number;
setData: React.Dispatch<React.SetStateAction<number[]>>;
};
const Row = memo((props: { index: number }) => {
const { value, setData } = StoreCtx.usePartialContext<PartialResult>(([data, setData], prevValue) => {
if (prevValue?.prevValue === data[props.index]) return prevValue;
return {
value: data[props.index] + Math.random(),
prevValue: data[props.index],
setData
};
}, [props.index]);
const handleChange = useCallback((evt: any) => {
setData(prevData => [
...prevData.slice(0, props.index),
+evt.target.value,
...prevData.slice(props.index + 1),
])
}, [props.index]);
return (
<div>
{Math.random().toFixed(2)}
<input type="number" value={value} onChange={handleChange} />
</div>
);
});
const ListRenderer = memo((props: { length: number }) => (
<>{Array.from({ length: props.length }).map((_, i) => (
<Row key={i} index={i} />
))}</>
));
export const ExamplePartialContextHeavy = (props: { store: ExampleStore }) => {
const [state] = props.store;
return (
<StoreCtx.Provider value={props.store}>
<div>if row will be updated, random values will change</div>
<pre>{`
Imagine we have something heavy inside selector and we want to decide when to update
Because usePartialContext pass previous result, we could decide when to update
`}</pre>
<ListRenderer length={state.length} />
</StoreCtx.Provider>
);
};