AI Hints
Home›React Tutorial›Cheat Sheets
React · Lesson 114 of 120

Common Patterns

Recipes.

⏱ 2 min read▶ Video at 1:34:05🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

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.

ProblemRecipe
Siblings share statelift it up
Prop drillingcontext
Loading dataeffect + states, or a library
Repeated logica custom hook
Values from statecalculate 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.

ChangeWrite
Add[...items, x]
Removeitems.filter(i => i.id !== id)
Update oneitems.map(i => i.id === id ? {...i, done} : i)
Object{ ...obj, city: "York" }
From previoussetN(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