-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample.context-selector.dead-props.tsx
More file actions
46 lines (39 loc) · 1.54 KB
/
Copy pathexample.context-selector.dead-props.tsx
File metadata and controls
46 lines (39 loc) · 1.54 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
import { memo, useCallback } from "react";
import { createContext as createSelectorContext, useContextSelector } from "use-context-selector";
import type { ExampleStore } from "./example";
const StoreCtx = createSelectorContext<ExampleStore>(undefined!);
const Row = memo((props: { index: number, value: number }) => {
// you should use multiple useContextSelector for proper work
const value = useContextSelector(StoreCtx, ([data, setData]) => data[props.index]);
const setData = useContextSelector(StoreCtx, ([data, setData]) => setData);
const handleChange = useCallback((evt: any) => {
setData(prevData => [
...prevData.slice(0, props.index),
+evt.target.value,
...prevData.slice(props.index + 1),
])
}, [props.index]);
if (props.value !== value) {
alert('dead prop');
}
return (
<div>
{props.value}
<input type="number" value={value} onChange={handleChange} />
</div>
);
});
export const ExampleContextSelectorDeadProps = (props: { store: ExampleStore }) => {
const [state] = props.store;
return (
<StoreCtx.Provider value={props.store}>
<a href="https://react-redux.js.org/api/hooks#stale-props-and-zombie-children" target="_blank">stale props</a>
<br />
<pre>You will see alert if dead prop found</pre>
<hr />
{state.map((_, i) => (
<Row key={i} index={i} value={state[i]} />
))}
</StoreCtx.Provider>
);
};