0% found this document useful (0 votes)
2 views

managing-state-via-third-party-libraries-slides

The document provides an overview of managing state in React applications using various third-party libraries, categorized into local, global, server, immutable, and form states. It discusses recommended libraries for each category, considerations for caching and fetching server data, and guidelines for deciding how to handle state. Additionally, it includes exercises for practical application of the concepts discussed.

Uploaded by

harsh090101kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

managing-state-via-third-party-libraries-slides

The document provides an overview of managing state in React applications using various third-party libraries, categorized into local, global, server, immutable, and form states. It discusses recommended libraries for each category, considerations for caching and fetching server data, and guidelines for deciding how to handle state. Additionally, it includes exercises for practical application of the concepts discussed.

Uploaded by

harsh090101kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Managing State with

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

Deciding how to handle state


Recommended exercises
To try the demos:
Demo
1. Download the exercise files
2. Open before
3. Run “npm install”
4. Import the demo in App.js
Local State
Goal: Manage Component State

Built into React Also consider


useState XState
Class state Enforce state transitions
useReducer Display transitions via state chart
refs Test logic in isolation
Derived state in render
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
Context vs Redux

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

Built into React Many use Also consider


Nothing fetch react-query
Axios swr
We wrapped fetch in a custom hook
Relay
Apollo
Server State: Questions to Ask

1. Should I cache data on the client for a certain period?

2. Should I load fresh data when the tab is refocused?

3. Should I load fresh data when the network reconnects?

4. Should I retry failed HTTP calls?

5. Should I return cached data, then fetch fresh data behind the scenes?

6. Should I handle server cache separately from app state?

7. Should I avoid refetching recently fetched data?

8. Should I prefetch data the user is likely to want?


Server State
Goal: Fetch and cache server data

react-query swr Relay Apollo

Any endpoint GraphQL focused


react-query and swr

Automatic, dedicated server cache


- Separate server-cache
- Invalidates and refetches stale data
Dedupes requests
Auto retries

Refetch on refocus / network reconnect


stale-while-revalidate

I’m okay with showing slightly stale data for a moment

1. Display cached record


2. Request fresh record behind the scenes
3. Display the fresh record if it’s newer
Immutable State
Goal: Enforce immutability

Built into React: Also consider:


Nothing Immer
We used plain JS Write “mutative” code
Plain JS
Small and easy to learn
Auto freezes
Immer Example

import produce from "immer"


const user = {
name: "Cory”,
};

const userCopy = produce(user, draft => {


draft.name= ”Cory2"
})

console.log(user.name); // Cory
console.log(userCopy.name) // Cory2
Form State
Goal: Manage Form State

Built into React: Also consider:


State Formik
Event handlers React Hook Form
Derived state Reduce form boilerplate
Enforce conventions
Eight Ways to Handle State in React Apps
When to use it
URL Sharable app location
Web storage Persist between sessions, one browser
Local state Only one component needs the state
Lifted state A few related components need the state
Derived state State can be derived from existing state
Refs DOM reference, state that isn’t rendered
Context Global or subtree state
Third party library Global state, Server state, Form state, etc.
Deciding How to Handle 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

Add backpacks to the store


Finish the checkout process
- Accept billing info and payment
- Save partially completed checkout
- Display final order confirmation

Display cart quantity in nav


Deduplicate requests in useFetchAll
Add init arg to useFetch hook
Try caching via react-query or swr
Thanks for watching!
@housecor

Courses by Cory
Global state
- Redux, Recoil

Summary Finite State


- XState

Server state
- react-query, swr, Relay, Apollo

Form state
- Formik, react-hook-form

Immutable state
- Immer, Immutable

You might also like