-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReact Basics.txt
More file actions
359 lines (283 loc) · 9.91 KB
/
React Basics.txt
File metadata and controls
359 lines (283 loc) · 9.91 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
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
React Basics Doc
(2) types of components:
Class Based
- have the ability to manage local state
- has access to component lifecycle methods
Functional (stateless)
- lightweight
- easy to test
- cannot manage local state
- cannot access lifecycle methods
Class Based Component
--------------------------------
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
...
}
}
componentDidMount() {
...
}
render() {
return (
<div>
Welcome to React
</div>
)
}
export default App
Functional Component (The Standard)
----------------------------------------------------
const App = (props) => {
return (
<div>
The Count is {props.count}
</div>
)
App.defaultProps = {
count:0
}
ReactDOM.render(<App count={5} />, document.getElementById('root'));
Common Conditional Rendering Patterns
------------------------------------------------------
[ Ternary Operator ]
- if true, rendering what is on the left side
- if falsey, render what is on the right
// Example
function App() {
let isLoggedIn = true;
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
</div>
);
}
export default App;
[ Logical && Operator ]
- if the left side is true, render what is on the right
- if the left side is false, do not evaluate what is on the right
{ isLoading && <ActivityIndicator /> }
[ Nullish Coalescence ]
- returns its right-hand side of the operand when its left-hand side operand is null or undefined
// Example
const nullValue = null;
const valA = nullValue ?? "default for A";
React Hooks
-----------------
- a hook is a simple function with some rules on where we can run them
- hooks return values
- should be defined at the top of the functional component
- if the action that I am performing needs to be aware of the some aspect of the lifecycle of the component that I invoking it in, it should be a hook
- if the action does not need to know about the context of the react component, then it can be a simple function
useState - allows me to use simple state in a stateless functional components
- when using the set operator for a piece of state, the state value is not immediately updated or available
- it will only be accessible at the next render
- trying to access the value before the next render will cause issues
useEffect - implements lifecycle methods in stateless functional components
// defines a effect that runs when the component is mounted and when the dependency value (isFinished) is updated
useEffect(() => {
console.log("isFinished: ", isFinished)
// check if there is a new best score
if (isFinished && score > bestScore) {
setBestScore(score)
}
}, [isFinished])
// defines an effect with an empty dependency array that will run ONCE ONLY when the component initially mounts
useEffect(() => {
console.log("Component is mounted!"
}, [ ] )
useRef - allows me to reference a value that’s not needed for rendering; this is valuable if I don't need the UI to change based on a value; state is used for values that need to update the UI when changed
useReducer - allows me to manage complex state and provide access to state to the components that need them
useContext - allows me to share values without manually passing props down from the parent
Handling Props
---------------------
Prop Drilling - practice of adding properties to a component with the sole purpose of allowing that component to pass those properties on to other components
Transforming List using Array.Map
----------------------------------------------
const dynamicMenu = [{
id: 1,
title: 'Dynamic Home',
href: '/home',
icon: 'home'
},
{
id: 2,
title: 'Dynamic Services',
href: '/services',
icon: 'services'
}]
<Menu menuList={dynamicMenu} />
function Menu({ menuList }) {
return (
<nav>
<ul className='menu'>
{menuList.map(({id, href, icon, title}) =>
<MenuItem key={id} href={href} icon={icon} children={title}></MenuItem>
)}
React Context
--------------------
- Wraps a number of components with a value that all descendant components can access without going through properties at all.
- A context in React consists of two parts. It needs a provider, that contains the values that you want to pass to any descendant component, and it needs a consumer, that you use in each descendant component that wants access to the provided value
Fetching Data
--------------------
- data fetching logic is stored in a separate module and brought in to the component that needs to use it
- think actions file for NextJs
- if any component that is wrapped in <Suspense> is throwing promises ("waiting on data to be retrieved") that component is said to be "SUSPENDING"
function App() {
return (
<div className="app-wrapper">
<div className="app">
<div className="details">
<ErrorBoundary>
<Suspense fallback={<ShipFallback />}>
<ShipDetails />
</Suspense>
</ErrorBoundary>
</div>
</div>
</div>
)
}
// initialize variable to hold results from promise below
let ship: Ship
// define a variable to hold the state of the promise getShip
// assign the results of the getShip function to the variable ship
const shipPromise = getShip(shipName).then((result) => {
ship = result
})
function ShipDetails() {
// if the ship hasn't loaded yet, throw the shipPromise
// React knows what to do with the promise based on its state (rejected, fulfilled, or still pending)
if (!ship) throw shipPromise
const ship = use(shipPromise) // use React's "use" hook instead which does all of the promise state checking for me
// the results of the ship object will be available to the ShipDetails component if the promise resolves successfully
return (
<div className="ship-info">
<div className="ship-info__img-wrapper">
<img
src={getImageUrlForShip(ship.name, { size: 200 })}
alt={ship.name}
/>
</div>
<section>
<h2>
{ship.name}
<sup>
{ship.topSpeed} <small>lyh</small>
</sup>
</h2>
</section>
<section>
{ship.weapons.length ? (
<ul>
{ship.weapons.map((weapon) => (
<li key={weapon.name}>
<label>{weapon.name}</label>:{' '}
<span>
{weapon.damage} <small>({weapon.type})</small>
</span>
</li>
))}
</ul>
) : (
<p>NOTE: This ship is not equipped with any weapons.</p>
)}
</section>
<small className="ship-info__fetch-time">{ship.fetchedAt}</small>
</div>
)
}
Suspense
--------------
- handling UI state while data is being fetched
- its best to show the user something (pending state) while asynchronous processes are taking place
- this typical involves rendering a skeleton of some sort to hold the place of the real object until the data fetching is completed (promises resolved)
- wrapping a component in a suspense component basically means "render this skeleton component until I resolve all data fetching related promises)
- it is also good to wrap suspense components with an Error Boundary so that any errors from rejected promises bubble up to the error boundary and are presented to the users accordingly
- as long as I am using a "promise" I can suspend on it
// ShipFallback is a skeleton component that displays while the real data is being fetched
function ShipFallback() {
return (
<div className="ship-info">
<div className="ship-info__img-wrapper">
<img src="/img/fallback-ship.png" alt={shipName} />
</div>
<section>
<h2>
{shipName}
<sup>
XX <small>lyh</small>
</sup>
</h2>
</section>
<section>
<ul>
{Array.from({ length: 3 }).map((_, i) => (
<li key={i}>
<label>loading</label>:{' '}
<span>
XX <small>(loading)</small>
</span>
</li>
))}
</ul>
</section>
</div>
)
}
Optimistic UI
----------------
- the art of showing the user that an action that they have performed has succeeded although the backend operations have not yet been completed
- example: i liked a tweet on twitter on a slow network along with thousands of other users; the heart turns red
- example: i clicked "Submit" on a form and the button switches to "Submitting..." while the asynchronous operations are happening behind the
scenes
- this often involves passing an "optimistic" or fake version of the real thing that is being created behind the scenes during a "transition"
- in this context we can use data that the user provides (name or image via a form) while we create the actual fully loaded object behind the scenes and display that after the fact
- useOptimistic hook allows me to update state during a transition (e.g. form submission)
function CreateForm({
setOptimisticShip,
setShipName,
}: {
setOptimisticShip: (ship: Ship | null) => void
setShipName: (name: string) => void
}) {
const [message, setMessage] = useOptimistic('Create')
return (
<div>
<p>Create a new ship</p>
<ErrorBoundary FallbackComponent={FormErrorFallback}>
<form
action={async (formData) => {
setMessage('Creating...')
setOptimisticShip(await createOptimisticShip(formData))
await createShip(formData, 2000)
setMessage('Created! Loading...')
setShipName(formData.get('name') as string)
}}
>
<div>
<label htmlFor="shipName">Ship Name</label>
<input id="shipName" type="text" name="name" required />
</div>
<div>
<label htmlFor="topSpeed">Top Speed</label>
<input id="topSpeed" type="number" name="topSpeed" required />
</div>
<div>
<label htmlFor="image">Image</label>
<input
id="image"
type="file"
name="image"
accept="image/*"
required
/>
</div>
<CreateButton children={message} />
</form>
</ErrorBoundary>
</div>
)
}