Skip to content

Commit 7136f58

Browse files
committed
➕ 2021-07-29-react-hooks-cheat-sheet
1 parent d7d4f8e commit 7136f58

File tree

1 file changed

+197
-0
lines changed

1 file changed

+197
-0
lines changed
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
---
2+
slug: react-hooks-cheat-sheet
3+
title: React Hooks Cheat Sheet
4+
author: Bunlong
5+
author_title: React Patterns Team
6+
author_url: https://github.com/Bunlong
7+
author_image_url: https://avatars1.githubusercontent.com/u/37023003?s=400&u=0049c6773040efb265cdf622076305f8b47facec&v=4
8+
tags: [hook]
9+
image: /img/react-server-component.png
10+
---
11+
12+
![React Hooks Cheat Sheet](/img/react-server-component.png "React Hooks Cheat Sheet")
13+
14+
## State Management
15+
16+
### useState()
17+
18+
Declare state.
19+
20+
```js
21+
const [name, setName] = useState('Initial value');
22+
```
23+
24+
Update state.
25+
26+
```js
27+
setName('New value'); // directly
28+
```
29+
30+
```js
31+
setName((value) => 'New' + value); // based on previous state
32+
```
33+
34+
<!--truncate-->
35+
36+
## Side Effects
37+
38+
### useEffect()
39+
40+
Triggers callback function only once when component is mounted.
41+
42+
```js
43+
useEffect( () => {
44+
// Side effects, HTTP request, setTimeout, ... etc.
45+
}, []);
46+
```
47+
48+
Triggers callback function when dependency 'VALUE' is changed.
49+
50+
```js
51+
useEffect(() => {
52+
// Side effects, HTTP request, setTimeout, ... etc.
53+
}, [value]);
54+
```
55+
56+
Cleanup side effects when component is unmounted.
57+
58+
```js
59+
useEffect(() => {
60+
let timeout = setTimeout(doSomething, 5000);
61+
return () => clearTimeout(timeout);
62+
}, [value]);
63+
```
64+
65+
## Memoize a Callback
66+
67+
### useCallback()
68+
69+
Return new function only when dependencies change.
70+
71+
```js
72+
const handleClick = useCallback(() => {
73+
doSomethingWith(param1, param2);
74+
}, [param1, param2]);
75+
```
76+
77+
Memoize callback for a dynamic list of elements.
78+
79+
```js
80+
const handleClick = useCallback((event) => {
81+
const button = event.target;
82+
const value = button.getAttribute('data-value');
83+
doSomethingWith(value);
84+
}, []);
85+
86+
<ul>
87+
{objects.map((obj) => (
88+
<li key={obj.id}>
89+
<button data-value={obj.value} onClick={handleClick}>
90+
{obj.value}
91+
</button>
92+
</li>
93+
))}
94+
</ul>
95+
```
96+
97+
## Memoize a Value
98+
99+
### useMemo()
100+
101+
Will trigger only when dependencies change.
102+
103+
```js
104+
const value = useMemo(() => {
105+
// evaluates only when param1 or param2 change
106+
return expensiveOperation(param1, param2);
107+
}, [param1, param2]);
108+
```
109+
110+
## Reference Element
111+
112+
### userRef()
113+
114+
userRef is like a "BOX" that can hold a mutable value in its current property.
115+
116+
```js
117+
const inputRef = useRef(null); // initialize
118+
...
119+
const onButtonClick = () => {
120+
// current points to input element
121+
inputRef.current.focus(); // get reference
122+
}
123+
124+
<input type="text" placeholder="Name" ref={inputRef} />
125+
<button onClick={onButtonClick}>Focus input</button>
126+
```
127+
128+
## Context API
129+
130+
### useContext()
131+
132+
Avoid props drilling using context API.
133+
134+
```js
135+
// create and export context
136+
export const ThemeContext = createContext(null);
137+
138+
// wrap parent component with context provider
139+
return (
140+
<ThemeContext.Provider value={{theme: 'dark}}>
141+
<App />
142+
</ThemeContext.Provider>
143+
);
144+
145+
// use context inside any child component
146+
const { theme } = useContext(ThemeContext);
147+
```
148+
149+
## Manage State
150+
151+
### useReducer()
152+
153+
Initialize a local state and create reducer.
154+
155+
```js
156+
const initialState = {
157+
value: 0
158+
};
159+
160+
const reducer = (state, action) {
161+
switch (action.type) {
162+
case 'increment':
163+
return { ...state, value: state.value + 1 };
164+
case 'set_to':
165+
return { ...state, value: state.value };
166+
default:
167+
throw new Error('Unhandled action');
168+
}
169+
};
170+
```
171+
172+
Create local state and dispatch actions.
173+
174+
```js
175+
const [state, dispatch] = useReducer(reducer, initialState);
176+
...
177+
<button onClick={() => dispatch({ type: 'increment' })} />
178+
<button onClick={() => dispatch({ type: 'set_to', value: 24 })} />
179+
<button><button>
180+
```
181+
182+
## Create Your Own Custom Hook
183+
184+
Custom hooks must start with `use`.
185+
186+
```js
187+
const useApiResult = (param) => {
188+
const [result, setResult] = useState(null);
189+
useEffect(() => {
190+
// your tasks
191+
}, [param]);
192+
return { result };
193+
};
194+
195+
// to use it in a component
196+
const { result } = useApiResult('some-param');
197+
```

0 commit comments

Comments
 (0)