0% found this document useful (0 votes)
9 views53 pages

state-management-in-react-native

The document discusses state management in React Native, focusing on hooks like useState and useEffect for managing component state and side effects. It also introduces the Context API for avoiding prop drilling and compares various state management libraries including Redux, Recoil, and Zustand, outlining their use cases and best practices. The document emphasizes choosing the appropriate state management solution based on the application's size and complexity.

Uploaded by

zavhiyacette
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views53 pages

state-management-in-react-native

The document discusses state management in React Native, focusing on hooks like useState and useEffect for managing component state and side effects. It also introduces the Context API for avoiding prop drilling and compares various state management libraries including Redux, Recoil, and Zustand, outlining their use cases and best practices. The document emphasizes choosing the appropriate state management solution based on the application's size and complexity.

Uploaded by

zavhiyacette
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

State Management in

React Native (useState


and useEffect):
Hooks
• are specially-implemented functions that let us add functionality
to React components beyond just creating and returning React
elements (React 16.8)
• aren't regular functions; they have to be written in a certain way
• useState - Persist state within a component function
• useReducer - Similar to useState, but for state that involves multiple sub-
values
• useEffect - Perform side effects within our component functions
• useRef - Wrap a mutable value
• Etc…
useState
• It allows us "remember" a value within a component function
• any variable we declare normally (i.e. with let myVar = ...) will get
reset since our component function may be called many times
throughout the lifecycle of the component
• With useState, React can remember a state variable for us, making
sure it gets passed into our component instance correctly.
• It allows the creation of a stateful variable AND a setter function to
update its value in the virtual DOM, but normal variables don’t.
• Allows a re-render of the virtual DOM once triggered
• [name, setName]
DOM
• short for Document Object Model
• is a programming interface for web documents, representing the
structure of HTML or XML documents as a hierarchical tree of objects
that can be manipulated by scripts like JavaScript
• is essentially a way to represent a web page or document in a
structured, object-oriented format.
• When a browser loads a web page, it creates a DOM representation
of the HTML or XML content, allowing JavaScript to access and
modify the elements, attributes, and content of the page.
Array destructuring
useEffect
• We use the useEffect hook to call functions with side effects within
our components.
• Think of it as some side code you want to perform
• It tells React to do some code when (pick one):
• This component re-renders
• This component mounts (mount = create and append it to the DOM)
• The state of a value
useEffect
• The useEffect hook takes 2 arguments:
• Callback/anonymous function/arrow function - a function with side effects
• dependencies - an optional array containing dependency values

• When our component function runs, the callback will be called if any
dependencies have changed since the last time the component
function ran.
• useEffect(function, [dependencies])
• 1. useEffect( ( ) => { } ) Runs after every re-render
• 2. useEffect( ( ) => { } , [ ] ) Runs only on mount
• 3. useEffect( ( ) => { } , [value] ) Runs only on mount + when value changes
No dependencies
Every time this
component re-
renders,
including
initially when
we mount the
component,
we will
perform the
code inside
useEffect()
Empty
Dependency
array

Only appears
once the
component
renders
Updater function

• A function passed as an argument to setState()


usually
• ex. setYear(y => y + 1)
• Allow for safe updates based on the previous
state
• Used with multiple state updates and
asynchronous functions
• Good practice to use updater functions for
consistency
Updater function

• Below, it uses the CURRENT state to calculate


the NEXT state
• Set functions DO NOT trigger an update
• React batches together state updates for
performance reasons
• NEXT state becomes the CURRENT state after an
update
Updater function

By naming convention
Updater function

• Now, it uses the PENDING state to calculate the


NEXT state
• React puts your updater function in a queue
• During the next render, it will call them in the
same order
1 or more dependency
State Management in
React Native (context API
createContext/useContext):
useContext
• React Hook that allows you to share values
between multiple levels of components without
passing props through each level

• If you have a lot of nested components, passing


props down to each level can become very
tedious, useContext avoids that
index

ChildA
ChildB
ChildC
ChildD
Set state variable and setter

ChildA
If we were using props…

ChildA
If we were using props…

ChildB

ChildC
If we were using props…

ChildD
Prop drilling
• the practice of passing data (props) down through multiple levels of components in a
component tree, even when some components don't directly use that data, just to reach
a deeply nested child component that needs it
• Imagine a parent component needs to pass data to a grandchild component, but
there's a child component in between. Instead of passing the data directly from
the parent to the grandchild, you pass the data from the parent to the child, and
then the child passes it down to the grandchild, even if the child component
doesn't use the data itself.
• Code that's harder to maintain and understand - Intermediate components
become "prop passers" and their purpose becomes unclear.
• Increased cognitive load for developers - It can be harder to follow the flow of data
through the component tree.
• Potential for unnecessary re-renders - If a component is passed a prop it doesn't
use, but that prop changes, the component will still re-render.
useContext
• React Hook that allows you to share values
between multiple levels of components without
passing props through each level

• Consumer component
• Provider component • import {useContext} from ‘react’;
• import {createContext} from ‘react’; • import {MyContext} from “@/ChildA”
• export const MyContext = createContext();
• const value =
• <MyContext.Provider value={value}> useContext(MyContext)
<Child />
</MyContext.Provider>
ChildA
ChildD
ChildC
Counter program
• Add, subtract, reset, change color
• Alternate between at least 5 different colors
• Use updater functions least 5 times each
• Terminal should log both the current number and the color
Dice roller program
• Button to roll two numbers randomly each between 1-6
• Roll value 1-2 = text color #1
• Roll value 3-4 = text color #2
• Roll value 5-6 = text color #3
• Terminal should log both the current numbers and their
respective colors
STATE
MANAGEMENT
IN
REACT NATIVE
18
WHAT IS REDUX ?
Redux is a predictable state container for JavaScript apps (including React
& React Native).

It helps manage global state in a centralized store using a unidirectional


data flow.

Ideal for large applications with complex state interactions.

GROUP 1
19
CORE CONCEPTS
Store

Actions

GROUP 1
20
CORE CONCEPTS
Reducers Data Flow (Unidirectional)

Components dispatch actions →


actions go to reducers → reducers
return new state → store updates
→ UI re-renders.

GROUP 1
EX: TODO APP 21
Action Store

Component (with useDispatch and useSelector)

Reducer
22
WHY REDUX TOOLKIT ?

Redux Toolkit (RTK) is the official, recommended way to write Redux logic.

It solves major issues in traditional Redux: boilerplate code, complex


configuration, and manual immutability handling.

RTK makes Redux easier, cleaner, and faster to use.

GROUP 1
23
KEY FEATURES
createSlice

GROUP 1
23
KEY FEATURES
configureStore

GROUP 1
24
KEY FEATURES
Simplified Reducers
Uses Immer under the hood so you can write
“mutating” code that is actually immutable.
No need for deep copying or manually managing
immutability.

GROUP 1
25
COMPARISON WITH TRADITIONAL REDUX
WHAT IS RECOIL AND RECOIL ROOT

Recoil is a state management library for React and React Native


applications. It's developed by Facebook and is designed to manage
global and shared state in a way that's simple, efficient, and scalable.

RecoilRoot is a required provider component when using Recoil. In order


for your components to access and share that state, you must wrap the
root of your app with RecoilRoot.
THE TWO CORE CONCEPTS OF RECOIL

ATOMS SELECTOR
WHAT IS A ZUSTAND

Zustand is a fast, lightweight, and scalable state management library for


React and React Native apps.
WHICH ONE SHOULD YOU CHOOSE FOR YOUR REACT NATIVE
PROJECT?

Consider Recoil if: You have a large, complex application where fine-grained
updates and a structured approach to state derivation are crucial for
performance and maintainability. The built-in debugging tools can also be a
big plus.

Consider Zustand if: You prefer a simpler, more lightweight solution with a
minimal API. It's excellent for projects of all sizes where you want to get up
and running quickly without a lot of overhead.
Best Practices & When to Use What

Small Apps → useState + useEffect

Medium Apps → Context API

Large Apps → Redux Toolkit / Recoil

Minimalist Approach → Zustand

You might also like