-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
561 lines (504 loc) · 18.6 KB
/
index.html
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="styles/fonts.css" />
<link rel="stylesheet" href="dist/reset.css" />
<link rel="stylesheet" href="dist/reveal.css" />
<link rel="stylesheet" href="dist/theme/dracula.css" />
<link rel="stylesheet" href="plugin/highlight/atom.css" />
<link rel="stylesheet" href="styles/theme.css" />
<link rel="stylesheet" href="styles/custom.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
<script id='keys'>
function processKeyDown (e) {
if (e.key === '1') {
const titleElement = document.getElementById('title');
const underlineElement = document.getElementById('line-1');
const stateElement = document.getElementById('state');
stateElement.style = 'transition: var(--transition);text-shadow: var(--shadow-white)';
setTimeout(() => {
underlineElement.style.display = 'flex';
underlineElement.classList.add('animate__slideInUp');
}, 500);
} else if (e.key === '4') {
const titleElement = document.getElementById('title-4');
const crossline = document.getElementById('line-4');
const newElement = document.getElementById('new-el-4');
setTimeout(() => {
crossline.style.display = 'flex';
crossline.classList.add('animate__zoomIn');
}, 500);
setTimeout(() => {
titleElement.style = 'transition: var(--transition);color: #ffffff80'
newElement.classList.add('animate__zoomIn');
newElement.style.display = 'flex';
}, 1200);
}
}
document.addEventListener('keydown', processKeyDown);
</script>
<style id='theme'>
/* individual styles, for this current talk */
#line-1 {
top: 8rem;
width: 20rem;
right: 0.2rem;
}
#line-4 {
top: 2.5rem;
left: 27rem;
width: 27rem;
}
#new-el-4 {
position: absolute;
top: -5rem;
left: 23rem;
font-weight: 600;
text-shadow: var(--shadow-title-pink);
display: none;
}
</style>
<title>React Hooks</title>
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<div class="title">
<div class='title-header'>
<span id="conversation" class='title-header-conversation' style="display:none;">Conversation</span>
<h2>React Hooks <span id='talk'>Talk<span></h2>
</div>
<h5 class="white">What, why, how and how <em>"not
to"</em></h5>
<div class="details">
<p class="p2 date">January 3, 2022</p>
<p class="p2 author">by Dmitry Melnikov</p>
</div>
<div class='one-two'>
<a target="_blank"
href="http://localhost:8888?print-pdf">print
version</a>
</div>
</div>
<aside class="notes">Welcome and intro speak</aside>
</section>
<section>
<div>
<h3>What is a hook?</h3>
<img src="materials/slide2_hook.jpeg" alt="Hook Image" style="width: 40%" />
<p>Any examples?</p>
</div>
<aside class="notes">Wiki: intercepting calls/events, middleware as pre/post hooks</aside>
</section>
<section>
<h3>Benefits of using hooks</h3>
</section>
<section>
<h3>Hooks in React</h3>
<ul>
<li>Difference from regular functions</li>
<li>Types</li>
<li>Rules of hooks</li>
</ul>
</section>
<section>
<h3>Difference from regular functions</h3>
</section>
<section>
<h3>Types of hooks</h3>
<div>
<p>Two types of hooks in React:</p>
<ul>
<li>built-in</li>
<li>custom</li>
</ul>
</div>
</section>
<section>
<section>
<h3>Rules of hooks</h3>
<div><a href="https://reactjs.org/docs/hooks-rules.html">from React docs</a></div>
<ul>
<li>only call hooks at the top level</li>
<li>only call hooks from React functions</li>
</ul>
<div class='super m1 emphasize'>⬐ what docs say ⬎</div>
</section>
<section>
<h4>Only Call Hooks at the Top Level</h4>
<p><mark>Don’t call Hooks inside loops, conditions, or nested functions.</mark></p>
<p>
Instead, always use Hooks at the top level of your React function, before any early returns. By following
this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what
allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
</p>
</section>
<section>
<h4>Only Call Hooks from React Functions</h4>
<p>Don’t call Hooks from regular JavaScript functions. Instead, you can:</p>
<ul>
<li>✅ Call Hooks from React function components.</li>
<li>✅ Call Hooks from custom Hooks (we’ll learn about them on the next page).</li>
</ul>
</section>
</section>
<section>
<h3>Built-in React hooks</h3>
<div>
<ul>
<li><a href="#/9">useState</a></li>
<li><a href="#/10">useEffect</a></li>
<li><a href="#/11">useCallback</a></li>
<li><a href="#/12">useMemo</a></li>
<li><a href="#/13">useLayoutEffect</a></li>
</ul>
</div>
<aside class="notes"></aside>
</section>
<section>
<section>
<h3 class="no-uppercase">useState</h3>
</section>
<section data-markdown>
<textarea data-template>
async vs sync way:
```js [1-5]
const [state, setState] = useState(0)
setState(state+1)
// or
setState(state => state+=1)
```
</textarea>
</section>
</section>
<section>
<section>
<h3 class='no-uppercase'>useEffect vs useLayoutEffect</h3>
<p>
<b>useEffect</b> runs <em>after react renders your component</em> and ensures that your effect callback does
not block browser painting.
</p>
</section>
<section>
<h3 class='no-uppercase'>useEffect vs useLayoutEffect</h3>
<p>
This differs from the behavior in class components where
<b>componentDidMount</b> and <b>componentDidUpdate</b> run synchronously
after rendering. It's more performant this way and most of the
time this is what you want. However, if your effect is mutating the
DOM (via a DOM node ref) and the DOM mutation will change the appearance
of the DOM node between the time that it is rendered and your effect
mutates it, then you don't want to use useEffect - <em>the user could see
a flicker when your DOM mutations take effect.</em>
</p>
</section>
<section>
<h3 class='no-uppercase'>useEffect vs useLayoutEffect</h3>
<p>
<b>useLayoutEffect</b> runs synchronously <em>immediately after React has performed all DOM mutations</em>.
This can be useful if you need to make DOM measurements (like getting the scroll position or other styles
for an element) and then make DOM mutations or trigger a synchronous re-render by updating state.
<b>useLayoutEffect runs BEFORE useEffect</b>
</p>
</section>
</section>
<section>
<section>
<h3 class="no-uppercase">useEffect</h3>
<p>
<b>useEffect</b> is not a lifecycle hook, it's a state sync tools - it synchronize side effects with
state, i.e. when a certain state changes, <b>useEffect</b> runs the side effects:
</p>
</section>
<section>
<img src="materials/dan_mental_model.jpg" />
</section>
<section data-markdown>
<textarea data-template>
### Issues
Incorrect dependency array:
```js [2|2,9|1-9]
useEffect(() => {
if (props.error) {
...
log.warn(props.message);
}
}, [props.message]);
```
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Issues
Reacting to prop change to call callback in props - should be done in parent
```js
export function Example({ value, callback }) {
useEffect(() => {
if (value) callback();
}, [value]);
return <></>;
}
```
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Issues
should be:
```js
export function Example() {
return <></>;
}
```
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Issues
Reacting to changes of local state - perform action together with state change:
```js [2|2,3-6|2,3-6,9|1-13]
export function Example({ initialValue, updateParent }) {
const [value, setValue] = useState(initialValue);
useEffect(() => {
if (value !== initialValue) updateParent(value);
}, [value]);
function handleChange(e) {
setValue(e.target.value);
}
return <input onChange={handleChange} value={value} />;
}
```
</textarea>
</section>
<section data-markdown>
<textarea data-template>
# Issues
should be:
```js [6,7|1-10]
export function Example({ initialValue, updateParent }) {
const [value, setValue] = useState(initialValue);
function handleChange(e) {
setValue(e.target.value);
updateParent(e.target.value);
}
return <input onChange={handleChange} value={value} />
}
```
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Correct use #1
```js [2-3|2-3,5-10|2-3,5-10,13|1-15]
const { store } = ...
useEffect(() => {
store.dispatch(...)
store.dispatch(...)
store.dispatch(...)
return () => {
store.dispatch(...);
};
}, []);
```
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Correct use #2
```js [6|6,9|1-11]
function handleKeys(e) {
// see slide about custom hooks
}
useEffect(() => {
globalThis.document.addEventListener('keydown', handleKeys);
return () => {
globalThis.document.removeEventListener('keydown', handleKeys);
};
}, []);
```
</textarea>
</section>
</section>
<section>
<section>
<h3 class='no-uppercase'>What is memoization?</h3>
</section>
<section>
<b>Memoization</b> or <b>memoisation</b> is an optimization technique used
primarily to speed up computer programs by storing the results of expensive
function calls and returning the <b>cached</b> result when the same inputs occur again.
</blockquote>
</section>
<section data-markdown>
<textarea data-template>
### useCallback
```js
const memoizedFn = useCallback((...args)=> {
// perform expensive calculations
}, [dependency])
const result = memoizedFn(arg1, arg2)
```
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### useMemo
```js
const memoizedValue = useMemo(()=> {
// perform epxensive calculations
return value
},[dependency])
cosole.log(memoizedValue)
```
</textarea>
</section>
</section>
<section>
<section>
<h3>Custom hooks</h3>
<p>When the logic need to be abstracted, but access to context is required. Examples:</p>
</section>
<section data-markdown>
<textarea data-template>
### useKeyPress
```js [1-16|2-15|3-9|11|13-15]
export function useKeyPress({ onEnter, onEscape, onArrowDown, onArrowUp, onKey }) {
useEffect(() => {
function handleKeys(e) {
if (e.key === 'Escape' && onEscape) onEscape(e);
if (e.key === 'Enter' && !e.shiftKey && onEnter) onEnter(e);
if (e.key === 'ArrowDown' && onArrowDown) onArrowDown(e);
if (e.key === 'ArrowUp' && onArrowUp) onArrowUp(e);
if (onKey) onKey(e.key);
}
globalThis.document.addEventListener('keydown', handleKeys);
return () => {
globalThis.document.removeEventListener('keydown', handleKeys);
};
}, [onEscape, onEnter, onArrowDown, onArrowUp, onKey]);
}
```
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### useWorkIsOverSprint
```js [1-11|2|4|6|8|10|1-11]
export function useWorkIsOverSprint() {
const { work, assigned } = useContextSelector(WorkContext, c => c);
const sprint = useSelector(getCurrentSprint);
if (!assigned || !sprint) return false;
const endDate = assigned.startDate.add(work.estimate, 'days');
return endDate.isAfter(sprint.endDate, 'days');
}
```
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### useWorkDays
```js
export function useWorkDays({ workToRender, engineer }: UseWorkDaysProps) {
const sprintDays = useSelector(getSprintDays);
const isDayOff = useSelector(getIsDayOff);
if (!workToRender || !engineer) return { days: [], lastDay: dayjs(), isOverSprint: false };
const { daysOff } = engineer;
const { work, startDate } = workToRender;
const days = sprintDays.map(day => {
const r = daysOff.find(d => d.isSame(day.date, 'date'));
if (!r) return day;
return { ...day, isOff: true };
});
let pointsLeft = work.estimate;
let lastDay = days[0];
const isOverSprint = false;
const shouldReturnDay = ({ date, isWeekend, isOff }: DbDate): boolean => {
if (!pointsLeft || isOff || isWeekend || isDayOff(date)) return true;
return false;
};
const mapper = (day: DbDate) => {
const { date } = day;
if (shouldReturnDay(day)) return day;
const isAlreadyFinished = startDate.add(pointsLeft, 'days').isBefore(date, 'date');
if (isAlreadyFinished) return day;
const isSameAsStart = date.isSame(startDate, 'date');
const isAfterStart = date.isAfter(startDate, 'date');
if (!isSameAsStart && !isAfterStart) return day;
if (isSameAsStart || (pointsLeft && isAfterStart)) {
pointsLeft -= 1;
if (!pointsLeft) lastDay = day;
return { ...day, isWork: true };
}
return day;
};
const result = days.map(mapper);
return { days: result, lastDay, isOverSprint };
}
```
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Usage
```js
const isOverSprint = useWorkIsOverSprint();
//
const { days } = useWorkDays({ engineer, workToRender });
```
</textarea>
</section>
</section>
<section>
<h3>Materials</h3>
<ul>
<li>
<a target="_blank" referrerpolicy="no-referrer" href="https://17.reactjs.org/docs/hooks-intro.html">React
Docs // Hooks</a>
</li>
<li>
<a target="_blank" referrerpolicy="no-referrer" href="https://usehooks.com/" title="useHooks">"useHooks"
collection</a>
</li>
<li>
<a target="_blank" referrerpolicy="no-referrer" href="https://epicreact.dev/myths-about-useeffect/">Myths
About useEffect</a>
</li>
<li><a target="_blank" referrerpolicy="no-referrer" href="https://www.youtube.com/watch?v=HPoC-k7Rxwo">Video:
Goodbye, useEffect: David Khourshid</a>
</li>
<li>
<a target="_blank" referrerpolicy="no-referrer"
href="https://julesblom.com/writing/react-hook-component-timeline">Timeline of a React Component With
Hooks</a>
</li>
</ul>
</section>
<section>
<h3>p.s.</h3>
</section>
<section>
<div style="display:flex;flex-flow:column">
<h3 class='r-fit-text'>
<video class="r-stretch" height='600' controls src="materials/find_out.mp4" type="video/mp4"></video>
</h3>
<a target="_blank" referrerpolicy="no-referrer"
href="https://twitter.com/rogerskaer/status/1576025818182332416?s=19">link</a>
</div>
</section>
</div>
</div>
<script src="dist/reveal.js"></script>
<script src="plugin/notes/notes.js"></script>
<script src="plugin/markdown/markdown.js"></script>
<script src="plugin/highlight/highlight.js"></script>
<script>
Reveal.initialize({
hash: true,
plugins: [RevealMarkdown, RevealHighlight, RevealNotes],
});
</script>
</body>
</html>