siddheshjadhav919123
22 views
32 slides
Oct 17, 2024
Slide 1 of 32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
About This Presentation
dcdc
Size: 5.04 MB
Language: en
Added: Oct 17, 2024
Slides: 32 pages
Slide Content
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 . Th e i n i t i a l s t a t e A f u n c t i o n t o s e t t h e i n i t i a l s t a te programmatically Th e s t a t e s n a p s h o t u s e d i n t h e co m p o n e n t r e - r e n d e r / r e - e v a l u a t i o n c y c l e A f u n c t i o n t h a t c a n b e u s e d t o d i spa t c h a n e w a c t i o n ( i . e . t r i gg e r a n u pda t e o f t he state)
u s e S t a t e ( ) v s u s e R e d uc e r () 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() Th e m a i n s t a t e m a n a g e m e n t “ t oo l ” G r e a t f o r i n d e p e n d e n t p i e c e s o f s t a t e / d a t a Great if state updates are easy and limited to a f e w k i nd s o f u pda t e s G r e a t i f y o u n ee d “ m o r e p o w e r ” S h o u ld b e c o n s i d e r e d i f y o u h a ve r e l a t e d p i e c e s o f s t a t e / da ta C a n b e h e l p f ul i f y o u h a ve m o r e c o m p l ex s t a t e u pd a t e s
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 Header CartModal 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 Header CartModal 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. Predictable Centralized Debuggable 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 Redux Mobx Recoil react-query swr Relay Apollo Immer Immutable.js Formik React Hook Form Mobx -state-tree mobx -react-lite Easy-peasy Overmindjs react-easy-state Effector react-sweet-state Freezer Undux Statux zustand 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 A n y e n dp o i n t G ra p h Q L fo c u s ed
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
F o r m i k R e a ct Hook Fo r m
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. D e c i d i n g H ow t o H a n d l e S t a t e