managing-state-via-third-party-libraries-slides
managing-state-via-third-party-libraries-slides
Third-party Libraries
Cory House
React Consultant and Trainer
@housecor | reactjsconsulting.com
Third Party State Libraries
Redux mobx-react-lite
Mobx Easy-peasy
Recoil Overmindjs
react-query react-easy-state
swr Effector
Relay react-sweet-state
Apollo Freezer
Immer Undux
Immutable.js Statux
Formik zustand
React Hook Form reatom
Mobx-state-tree
Recommended libraries
- Local state
Agenda - Global state
- Server state
- Immutable state
- Form state
Context VS Redux
Simple values that rarely change Complex values that change often
Global state/funcs App state is updated frequently
Built in to React Complex state update logic
Middleware
Medium to large codebase
Large team
Global State
Goal: Share state or functions globally
Built into React: Also consider:
Lift state Redux
Context Complex app with many state transitions
Want to cache and share local data
Middleware for cross-cutting concerns
MobX
Optimize derived state
Manage state outside React
Recoil
Many frequently changing elements
Avoid updating unrelated parts of the UI
Global State
Goal: Share state or functions globally
Built into React: Also consider:
Lift state Zustand
Context Simple Redux alternative
Jotai
Simple Recoil alternative
Valtio
Simple Mobx alternative
Server State
Goal: Fetch and cache server data
5. Should I return cached data, then fetch fresh data behind the scenes?
console.log(user.name); // Cory
console.log(userCopy.name) // Cory2
Form State
Goal: Manage Form State
1. Does it belong in the URL? (current page, current record, sorting, scroll location...)
Keep URL-related state in the URL.
2. Want to persist data across sessions or make data available offline?
Consider web storage (localStorage, IndexedDB, etc)
3. Is it server data?
Try react-query or swr. Using GraphQL? Then also consider Relay / Apollo.
4. Is it a DOM element reference, state that doesn’t change, or not rendered at all?
Use a ref.
5. Can it be derived from existing props, state, URL, etc?
Derive it “on-the-fly” as part of each render (memoize if expensive).
6. Does only one component use the data?
Use local state.
7. Do a few related components use it?
Store state in a common parent.
8. Is it global state? Consider, in order:
Store in App’s root component, context, or separate library like Redux.
Exercises
Courses by Cory
Global state
- Redux, Recoil
Server state
- react-query, swr, Relay, Apollo
Form state
- Formik, react-hook-form
Immutable state
- Immer, Immutable