React · Lesson 114 of 120
Common Patterns
Recipes.
Some problems come up in every app. Here are the recipes we used, in one place.
- Same problems
- Every app
- Recipes
Recipes
Share state between siblings by lifting it up. Avoid prop drilling with context. Load data with an effect, plus loading and error state, or a data library. Reuse logic with a custom hook. And never store what you can calculate.
| Problem | Recipe |
|---|---|
| Siblings share state | lift it up |
| Prop drilling | context |
| Loading data | effect + states, or a library |
| Repeated logic | a custom hook |
| Values from state | calculate in render |
Updating state safely
Add to an array with spread. Remove with filter. Update one item with map. Change an object with spread and a new value. And use an updater when the next value depends on the last.
| Change | Write |
|---|---|
| Add | [...items, x] |
| Remove | items.filter(i => i.id !== id) |
| Update one | items.map(i => i.id === id ? {...i, done} : i) |
| Object | { ...obj, city: "York" } |
| From previous | setN(n => n + 1) |
Summary
Lift state, use context, derive values, and update immutably. Next, React interview questions.
Key takeaways- Lift
- Derive
- Immutable
Next up: React Interview Questions — part one