-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample.tsx
More file actions
76 lines (68 loc) · 1.78 KB
/
Copy pathexample.tsx
File metadata and controls
76 lines (68 loc) · 1.78 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import React, { useMemo } from "react";
import ReactDOM from "react-dom";
import { defaultState, useItemsStore } from "./example-store";
function ItemScreen() {
const { Provider } = useItemsStore;
return (
<Provider initialState={defaultState}>
<Item />
<hr />
<MethodsConsumerNoRerendering />
<hr />
<StateSlice />
</Provider>
);
}
function Item() {
const { state, effects } = useItemsStore();
return (
<div>
<h1>Item Screen</h1>
{state.loading && <p>Loading...</p>}
{state.error && <p>Error loading 😕</p>}
{state.data && <p>Data loaded 🎆: {state.data}</p>}
<button onClick={effects.loadItem}>Load item</button>
</div>
);
}
let methodsConsumerRerenderingCounter = 0;
function MethodsConsumerNoRerendering() {
const { effects } = useItemsStore();
return useMemo(
() => (
<div>
<p>
This component using only methods and should not be re-rendered ever
</p>
<p>{`Rerender counter: ${methodsConsumerRerenderingCounter++}`}</p>
<button onClick={effects.loadItem}>
Load item from memo component
</button>
</div>
),
[effects]
);
}
let stateSliceRerenderingCounter = 0;
function StateSlice() {
const {
state: { error },
effects
} = useItemsStore();
return useMemo(
() => (
<div>
<h5>Check re-renders with state slicing</h5>
<p>
This component rerenders only on state.error changes (error on load)
</p>
<p>{`Rerender counter: ${stateSliceRerenderingCounter++}`}</p>
<button onClick={effects.loadItem}>
Load item from memo component
</button>
</div>
),
[error]
);
}
ReactDOM.render(<ItemScreen />, document.querySelector(".app"));