-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUseRefHook.tsx
60 lines (54 loc) · 1.46 KB
/
UseRefHook.tsx
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
/* eslint-disable react/display-name */
import { forwardRef, useEffect, useRef } from 'react';
// Not possible -> Prints a warning
/*
const Component = ({ ref }: any) => {
return <div>A component we catch the reference</div>;
};
*/
const Component = forwardRef<HTMLDivElement>((props, ref) => {
return (
<div ref={ref} {...props}>
A component we catch the reference
</div>
);
});
export default function UseRefHook() {
const element = useRef<HTMLDivElement>(null);
const component = useRef<HTMLDivElement>(null);
const stateWithoutReRendering = useRef({ foo: 'bar' });
console.log('Inside the Refs:', {
element,
component,
stateWithoutReRendering,
});
useEffect(() => {
element.current?.setAttribute('style', 'background-color: green');
component.current?.setAttribute('style', 'background-color: aqua');
}, [element, component]);
useEffect(() => {
console.log('Update Component!');
}, [stateWithoutReRendering]);
return (
<>
<h2
onClick={() => {
stateWithoutReRendering.current = {
...stateWithoutReRendering.current,
foo: 'baz',
};
console.log('Inside the Refs: after click', {
element,
component,
stateWithoutReRendering,
});
}}
>
<pre style={{ display: 'inline-block' }}>useRef</pre>-Component
<div ref={element}>An element we catch the reference</div>
<Component ref={component} />
<div>Ref. as state: {JSON.stringify(stateWithoutReRendering)}</div>
</h2>
</>
);
}