STATE MANAGEMENT
IN REACT
By-Siddhesh Jadhav
1
2
useState() Yields An Array With Two Elements
And it will always be exactly two
elements
const stateArray = useState(‘Please click a button’);
Array produced and returned by React’s
useState() function
Contains exactly two elements
3
Manage State
const [counter, setCounter] = useState(0);
Current state
value
Provided by React
State updates lead to new state
values
State updating
function
Initial state
value
Stored by React
May change if the
component function
is
Executed again
(as the component function executes
again)
function in which useState() was
called
Manage data & “tell” React to re-execute a component
function via React’s useState() Hook
What’s a Ref?
Reference an HTML element
Store a value that’s stable between renders
Can mutate the ref’s value directly
Don’t cause a re-render when they change
5
DOM element reference
State that isn’t rendered/doesn’t change “Instance variables”
in function components:
- Keep data between renders
- Storing a previous value
- Track if component is mounted
- Hold HTTP request cancel token
- Reference a 3rd party library instance
- Debounce a call / declare local cache
- Store flag that something happened
- Store value used in useEffect
When to Use a Ref
6
State vs Refs
State Refs
Causes component re-evaluation (re-
execution) when changed
Should be used for values that are directly
reflected in the
UI
Should not be used for “behind the
scenes” values that have no direct UI
impact
Do not cause component re-evaluation
when
changed
Can be used to gain direct DOM element
accessing certain browser APIs)
Can be used to expose API functions from
your
components
Should not be used for managing values
that have a direct UI
impact
Introducing useReducer() for State
Management
Sometimes, you have more complex state – for example if it got
multiple states, multiple ways of changing it or dependencies to
other states
useState() then often becomes hard or error-prone to use – it’s easy
to write bad, inefficient or buggy code in such scenarios
useReducer() can be used as a replacement for useState() if you
need “more powerful state management”
Understanding useReducer()
const [state, dispatchFn] = useReducer(reducerFn, initialState, initFn);
(prevState, action) => newState
A function that is triggered automatically once an action is
dispatched (via dispatchFn()) – it receives the latest
state snapshot and should return the new, updated state.
The initial
state
A function to
set the initial
state
programmaticall
y
The state
snapshot used in
the component
re-
render/ re-
evaluation
cycle
A function that
can be used to
dispatch a new
action (i.e.
trigger an
update of the
state)
useState() vs useReducer()
Generally, you’ll know when you need useReducer() ( when using
useState() becomes cumbersome or you’re getting a lot of bugs/
unintended behaviors)
useState() useReducer()
The main state management
“tool”
Great for independent pieces of state/
data
Great if state updates are easy and limited
to a few kinds of updates
Great if you need “more
power”
Should be considered if you have
related pieces of state/ data
Can be helpful if you have more
complex state updates
10
Advanced State Management
• The Problem Of Shared State: Prop Drilling
• Sharing State with Context Managing
• Complex State with Reducers
Most React Apps Consist Of Multiple Components
Shop
Product
App
Prop
Drilling
Passing
shared data
through
multiple
components
layers Cart
Heade
r
CartModa
l
Cart State
Update Cart
Display Cart
onUpdateCart
Prop
onUpdateCart
Prop
cart Prop
cart Prop
cart Prop
Most React Apps Consist Of Multiple Components
Shop
Product
App
Cart
Context
Cart
Heade
r
CartModa
l
Cart State
Update Cart
Display Cart
onUpdateCart
Prop
onUpdateCart
Prop
cart Prop
cart Prop
cart Prop
Most React Apps Consist Of Multiple Components
Shop
Product
App
Cart
Context
Cart
Heade
r
CartModa
l
Cart State
Update Cart
Display Cart
What Is Cross-Component & App-Wide State?
Local State Cross-component State
Or: React Context or
Redux
App-wide State
Should be managed inside
the /
component via
State belongs to a single
component
E.g., listening to user input on
an
input field or toggling a “show
more details”
field
Requires “prop
drilling”
State affecting multiple
components
E.g., open / closed state of a
modal overlay
Requires “prop
drilling”
State affecting the entire app
E.g., user authentication status
or
chosen
theme
useState()
useReducer()
A state management system
for cross-component
or app-wide state
Don’t we have React Context already?
Redux
React Context Has Some Potential Disadvantages
Complex Setup & Management Performance
In more complex apps, using React
Context can lead to deeply nested or “fat”
“Context Provider”
components
React Context is not optimized for
high- frequency state changes
Potential Problem: Complex Providers
Potential Problem: Deeply Nested Providers
19
What is Redux?
• A predictable state container for JavaScript apps.
• Centralized store that holds the entire state of the app.
• Unidirectional data flow with actions, reducers, and state.
• Suitable for complex applications.
20
Pros of Redux
• The advantages of Redux include a centralized store, easier
debugging with time travel, and the ability to use middleware
for side effects. It also has a strong community and extensive
ecosystem, providing many tools and libraries.
Predictabl
e
Centralize
d
Debuggab
le
Flexible
Redux helps you write
applications that behave
consistently, run in
different environments
(client, server, and native),
and are easy to test.
Centralizing your
application's state and logic
enables powerful
capabilities like undo/redo,
state persistence, and
much more.
The Redux DevTools make it
easy to trace when, where,
why, and how your
application's state changed.
Redux's architecture lets you
log changes, use "time-travel
debugging", and even send
complete error reports to a
server.
Redux works with any UI layer,
and has a large ecosystem of
addons to fit your needs.
21
1.Declare state in the
component that needs it.
2. Child components need the
state?
Pass state down via props.
3. Non-child components need
it?
Lift state to common parent.
4. Passing props getting
annoying?
Consider context, Redux.
State: Start Local
How to Manage State in React
22
Managing State with Third-party Libraries
1. Redux
2. Mobx
3. Recoil
4. react-query
5. swr
6. Relay
7. Apollo
8. Immer
9. Immutable.js
10.Formik
11.React Hook
Form
12.Mobx-state-tree
13.mobx-react-lite
14.Easy-peasy
15.Overmindjs
16.react-easy-state
17.Effector
18.react-sweet-state
19.Freezer
20.Undux
21.Statux
22.zustand
23.reatom
23
Built into React
useState
Class state
useReducer
refs
Derived state in render
Local State
Manage Component State
Also consider XState
• Enforce state
transitions
• Display transitions via state chart Test logic in
isolation
24
Global State
Share state or functions globally
Built into React
Lift state
Context
Also consider
Redux
• 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
25
Global State
Share state or functions globally
Built into React
Lift state
Context
Also consider:
Zustand
Simple Redux
alternative
Jotai
Simple Recoil alternative
Valtio
Simple Mobx alternative
26
Server State
Fetch and cache server data
Many use
fetch
Axios
Also consider
react-query
swr
Relay
Apollo
Built into React
Nothing
react-query Apollo
swr Relay
Server State
Fetch and cache server data
Any
endpoint
GraphQL
focused
Form State
Goal: Manage Form State
Built into React:
State
Event handlers
Derived state
Also consider:
Formik
React Hook Form
Reduce form boilerplate
Enforce conventions
Formi
k
React Hook
Form
When to use it
Eight Ways to Handle State in React Apps
URL
Web storage
Local state
Lifted state
Derived state
Refs
Context
Third
party
library
Sharable app location
Persist between sessions, one browser
Only one component needs the state
A few related components need the state
State can be derived from existing state
DOM reference, state that isn’t rendered
Global or subtree state
Global state, Server state, Form state, etc.
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.
Deciding How to Handle
State
32

STATE MANAGEMENT IN REACT [Autosaved].pptx

  • 1.
  • 2.
    2 useState() Yields AnArray With Two Elements And it will always be exactly two elements const stateArray = useState(‘Please click a button’); Array produced and returned by React’s useState() function Contains exactly two elements
  • 3.
    3 Manage State const [counter,setCounter] = useState(0); Current state value Provided by React State updates lead to new state values State updating function Initial state value Stored by React May change if the component function is Executed again (as the component function executes again) function in which useState() was called Manage data & “tell” React to re-execute a component function via React’s useState() Hook
  • 4.
    What’s a Ref? Referencean HTML element Store a value that’s stable between renders Can mutate the ref’s value directly Don’t cause a re-render when they change
  • 5.
    5 DOM element reference Statethat isn’t rendered/doesn’t change “Instance variables” in function components: - Keep data between renders - Storing a previous value - Track if component is mounted - Hold HTTP request cancel token - Reference a 3rd party library instance - Debounce a call / declare local cache - Store flag that something happened - Store value used in useEffect When to Use a Ref
  • 6.
    6 State vs Refs StateRefs Causes component re-evaluation (re- execution) when changed Should be used for values that are directly reflected in the UI Should not be used for “behind the scenes” values that have no direct UI impact Do not cause component re-evaluation when changed Can be used to gain direct DOM element accessing certain browser APIs) Can be used to expose API functions from your components Should not be used for managing values that have a direct UI impact
  • 7.
    Introducing useReducer() forState Management Sometimes, you have more complex state – for example if it got multiple states, multiple ways of changing it or dependencies to other states useState() then often becomes hard or error-prone to use – it’s easy to write bad, inefficient or buggy code in such scenarios useReducer() can be used as a replacement for useState() if you need “more powerful state management”
  • 8.
    Understanding useReducer() const [state,dispatchFn] = useReducer(reducerFn, initialState, initFn); (prevState, action) => newState A function that is triggered automatically once an action is dispatched (via dispatchFn()) – it receives the latest state snapshot and should return the new, updated state. The initial state A function to set the initial state programmaticall y The state snapshot used in the component re- render/ re- evaluation cycle A function that can be used to dispatch a new action (i.e. trigger an update of the state)
  • 9.
    useState() vs useReducer() Generally,you’ll know when you need useReducer() ( when using useState() becomes cumbersome or you’re getting a lot of bugs/ unintended behaviors) useState() useReducer() The main state management “tool” Great for independent pieces of state/ data Great if state updates are easy and limited to a few kinds of updates Great if you need “more power” Should be considered if you have related pieces of state/ data Can be helpful if you have more complex state updates
  • 10.
    10 Advanced State Management •The Problem Of Shared State: Prop Drilling • Sharing State with Context Managing • Complex State with Reducers
  • 11.
    Most React AppsConsist Of Multiple Components Shop Product App Prop Drilling Passing shared data through multiple components layers Cart Heade r CartModa l Cart State Update Cart Display Cart onUpdateCart Prop onUpdateCart Prop cart Prop cart Prop cart Prop
  • 12.
    Most React AppsConsist Of Multiple Components Shop Product App Cart Context Cart Heade r CartModa l Cart State Update Cart Display Cart onUpdateCart Prop onUpdateCart Prop cart Prop cart Prop cart Prop
  • 13.
    Most React AppsConsist Of Multiple Components Shop Product App Cart Context Cart Heade r CartModa l Cart State Update Cart Display Cart
  • 14.
    What Is Cross-Component& App-Wide State? Local State Cross-component State Or: React Context or Redux App-wide State Should be managed inside the / component via State belongs to a single component E.g., listening to user input on an input field or toggling a “show more details” field Requires “prop drilling” State affecting multiple components E.g., open / closed state of a modal overlay Requires “prop drilling” State affecting the entire app E.g., user authentication status or chosen theme useState() useReducer()
  • 15.
    A state managementsystem for cross-component or app-wide state Don’t we have React Context already? Redux
  • 16.
    React Context HasSome Potential Disadvantages Complex Setup & Management Performance In more complex apps, using React Context can lead to deeply nested or “fat” “Context Provider” components React Context is not optimized for high- frequency state changes
  • 17.
  • 18.
    Potential Problem: DeeplyNested Providers
  • 19.
    19 What is Redux? •A predictable state container for JavaScript apps. • Centralized store that holds the entire state of the app. • Unidirectional data flow with actions, reducers, and state. • Suitable for complex applications.
  • 20.
    20 Pros of Redux •The advantages of Redux include a centralized store, easier debugging with time travel, and the ability to use middleware for side effects. It also has a strong community and extensive ecosystem, providing many tools and libraries. Predictabl e Centralize d Debuggab le Flexible Redux helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. Centralizing your application's state and logic enables powerful capabilities like undo/redo, state persistence, and much more. The Redux DevTools make it easy to trace when, where, why, and how your application's state changed. Redux's architecture lets you log changes, use "time-travel debugging", and even send complete error reports to a server. Redux works with any UI layer, and has a large ecosystem of addons to fit your needs.
  • 21.
    21 1.Declare state inthe component that needs it. 2. Child components need the state? Pass state down via props. 3. Non-child components need it? Lift state to common parent. 4. Passing props getting annoying? Consider context, Redux. State: Start Local How to Manage State in React
  • 22.
    22 Managing State withThird-party Libraries 1. Redux 2. Mobx 3. Recoil 4. react-query 5. swr 6. Relay 7. Apollo 8. Immer 9. Immutable.js 10.Formik 11.React Hook Form 12.Mobx-state-tree 13.mobx-react-lite 14.Easy-peasy 15.Overmindjs 16.react-easy-state 17.Effector 18.react-sweet-state 19.Freezer 20.Undux 21.Statux 22.zustand 23.reatom
  • 23.
    23 Built into React useState Classstate useReducer refs Derived state in render Local State Manage Component State Also consider XState • Enforce state transitions • Display transitions via state chart Test logic in isolation
  • 24.
    24 Global State Share stateor functions globally Built into React Lift state Context Also consider Redux • 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
  • 25.
    25 Global State Share stateor functions globally Built into React Lift state Context Also consider: Zustand Simple Redux alternative Jotai Simple Recoil alternative Valtio Simple Mobx alternative
  • 26.
    26 Server State Fetch andcache server data Many use fetch Axios Also consider react-query swr Relay Apollo Built into React Nothing
  • 27.
    react-query Apollo swr Relay ServerState Fetch and cache server data Any endpoint GraphQL focused
  • 28.
    Form State Goal: ManageForm State Built into React: State Event handlers Derived state Also consider: Formik React Hook Form Reduce form boilerplate Enforce conventions
  • 29.
  • 30.
    When to useit Eight Ways to Handle State in React Apps URL Web storage Local state Lifted state Derived state Refs Context Third party library Sharable app location Persist between sessions, one browser Only one component needs the state A few related components need the state State can be derived from existing state DOM reference, state that isn’t rendered Global or subtree state Global state, Server state, Form state, etc.
  • 31.
    1. Does itbelong 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. Deciding How to Handle State
  • 32.