SlideShare a Scribd company logo
SLIDES FOR
THEORY
LECTURES
(
DON’T SKIP THEM, THEY ARE
SUPER IMPORTANT 🤓)
Subscribe here
Follow me here
📖 TABLE OF CONTENTS
:
THEORY LECTURES
(
CLICK THE TITLES
)
Watch Before You Start!
Why Do front-end Frameworks exist?
What is React?
Setting Up a New React Project: The Two Options
Components as Building Blocks
What is JSX?
Separation of Concerns
Props, Immutability, and One-Way Data Flow
The Rules of JSX
Section Summary
What is State in React?
The Mechanics of State
More Thoughts About State
+
State Guidelines
State vs. Props
What is "Thinking in React"?
Fundamentals of State Management
Derived State
The children Prop: Making a Reusable Button
How to Split a UI Into Components
Component Categories
Component Composition
Props as a Component API
Components, Instances, and Elements
How Rendering Works: Overview
How Rendering Works: The Render Phase
How Rendering Works: The Commit Phase
How Diffing Works
The Key Prop
Rules for Render Logic: Pure components
State Update Batching
How Events Work in React
Libraries vs. Frameworks & The React Ecosystem
Section Summary: Practical Takeaways
The Component Lifecycle
A First Look at Effects
The useEffect Dependency Array
The useEffect Cleanup Function
React Hooks and Their Rules
useState Summary
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
33
34
35
36
37
38
39
📖 TABLE OF CONTENTS
:
THEORY LECTURES
(
CLICK THE TITLES
)
Managing State With useReducer
Section Summary: useState vs. useReducer
Routing and Single-Page Applications
(
SPAs)
Styling Options For React Applications
What is the Context API?
Thinking In React: Advanced State Management
Performance Optimization and Wasted Renders
Understanding memo
Understanding useMemo and useCallback
Optimizing Bundle Size With Code Splitting
Don't Optimize Prematurely!
useEffect Rules and Best Practices
Introduction to Redux
Redux Middleware and thunks
What is Redux Toolkit
(
RTK
)
?
Redux vs. Context API
Application Planning (“Fast React Pizza Co.”)
What is Tailwind CSS?
Application Planning (“The Wild Oasis”)
What is Supabase?
Modeling Application State
What is React Query?
An Overview of Reusability in React
Introducing Another Hook: useRef
What are Custom Hooks? When to Create One?
Class Components vs. Function Components
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
An Overview of Server-Side Rendering
(
SSR
)
The Missing Piece: Hydration
What is Next.js?
What are React Server Components?
(
RSC Part 1
)
How RSC Works Behind the Scenes
(
RSC Part 2
)
RSC vs. SSR
:
How are They Related?
(
RSC Part 3
)
Project Planning: "The Wild Oasis" Website
What is React Suspense?
Types of SSR
:
Static vs. Dynamic Rendering
Partial Pre-Rendering
How Next.js Caches Data
Blurring the Boundary Between Server and Client
What is Middleware in Next.js?
66
67
68
69
70
71
72
73
74
75
76
77
78
What are Server Actions?
79
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
WELCOME, WELCOME,
WELCOME!
SECTION
LECTURE
WELCOME, WELCOME, WELCOME!
WATCH BEFORE YOU START!
✌ This course is for everyone! So please don’t write a bad review right away if the course is too easy,
or too hard, or progressing too slow, or too fast for you
✌ To make the course perfect for YOU
:
rewatch lectures, jump to other sections, watch the course
with slower or faster speed, or ask questions
Please don’t be that person. Everyone
is different... Unless the course is
truly terrible (it’s not 😛)
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
😱 You don’t need to watch the entire course in order to learn React! If you are in a hurry, can cut the
course length in HALF by skipping optional sections and practice parts
👩💻 You need to code along with me! You will learn ZERO React skills by just sitting and watching me
code. You really have to write code YOURSELF!
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
😅 In the first sections of the course, don’t worry about WHY and HOW things work, or about React
“best practices”. While learning, we just want to make things WORK. We will worry about everything
else later in the course
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
⁉ If you have a problem or a question, start by trying to solve it yourself! This is essential for your
progress. If you can’t solve it, check the Q&A section. If that doesn’t help, you can ask a new
question. Use a short description, and post code on codesandbox.io
1
2
3
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
⏳ Before moving on from a section, make sure that you understand exactly what was covered. Take
a break, review the code we wrote, review your notes, review the projects we built, and maybe even
write some code yourself
✅
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
✅
✅
🖥 I recorded this course on a Mac, but everything works the exact same way on Windows or Linux.
If something doesn’t work on your computer, it’s NOT because you’re using a different OS
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
😍 Most importantly, have fun! It’s so rewarding to see an app come to life that YOU have built YOURSELF!
So if you’re feeling frustrated, stop whatever you’re doing, and come back later!
And I mean REAL fun 😅
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
PART 01
—
REACT
FUNDAMENTALS
A FIRST LOOK AT
REACT
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
A FIRST LOOK AT REACT
WHY DO FRONT
-
END
FRAMEWORKS EXIST?
THE RISE OF SINGLE
-
PAGE APPLICATIONS
👩💻 CLIENT / FRONT
-
END
🌐 SERVER / BACK
-
END
BROWSER
DATA
VIEW
RENDER
WEBPAGE
SERVER
-
SIDE RENDERING
CLIENT
-
SIDE RENDERING
The “old” way (but now
getting modern again…)
The “modern” way
BROWSER
VIEW
RENDER
WEBPAGE
API
DATA
👉 Single-Page Application
(
SPA
)
👉 Developers started writing more
and more JS code, which led to…
SINGLE
-
PAGE APPLICATIONS WITH VANILLA JAVASCRIPT?
Handling data + displaying
data in a user interface
👉 Front-end web applications are all about…
User interface needs to
stay in sync with data
Very hard problem to solve!
DATA UI
KEEPING UI IN SYNC WITH DATA
☝ Keeping UI
and data in sync
would be virtually
impossible with
just vanilla
JavaScript
DATA
DATA
DATA
DATA
??
Piece of data
=
Piece of state
PROBLEMS WITH
SINGLE
-
PAGE APPLICATIONS WITH VANILLA JAVASCRIPT?
Handling data + displaying
data in a user interface
👉 Front-end web applications are all about…
User interface needs to
stay in sync with data
Very hard problem to solve!
1
Requires lots of direct DOM manipulation and
traversing (imperative) 👉 “Spaghetti code” 🍝
2
Data (state) is usually stored in the DOM, shared
across entire app 👉 Hard to reason + bugs 🐛
DATA UI
1 JavaScript front-end frameworks exist because…
KEEPING A USER INTERFACE IN SYNC WITH DATA
IS REALLY HARD AND A LOT OF WORK
Front-end frameworks solve this problem and take hard work away from developers 🎉
WHY DO FRONT
-
END FRAMEWORKS EXIST?
2
They enforce a “correct” way of structuring and writing code (therefore contributing to
solving the problem of “spaghetti code” 🍝)
3 They give developers and teams a consistent way of building front-end applications
DATA UI
Different approaches, same goal
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
A FIRST LOOK AT REACT
WHAT IS REACT?
WHAT IS REACT?
REACT
JAVASCRIPT LIBRARY FOR BUILDING
USER INTERFACES
WHAT IS REACT?
REACT
EXTREMELY POPULAR, DECLARATIVE,
COMPONENT
-
BASED, STATE
-
DRIVEN JAVASCRIPT
LIBRARY FOR BUILDING USER INTERFACES,
CREATED BY FACEBOOK 🤔 🤯 🤣
👉 Components are the building blocks of user interfaces in React
REACT IS BASED ON COMPONENTS
👉 We build complex UIs by building and combining multiple components
Webpage
Component 1
Component 2
Component 3
Based on components
Extremely popular
JavaScript library
State-driven
Declarative
Created by facebook
REACT IS BASED ON COMPONENTS
NavBar Search
Map
Results
Listing
Listing
Listing
Based on components
Extremely popular
JavaScript library
State-driven
Created by facebook
Declarative
REACT IS DECLARATIVE
👉 We describe how components
look like and how they work using
a declarative syntax called JSX
👉 Declarative: telling React what a
component should look like,
based on current data/state
👉 React is abstraction away from
DOM
:
we never touch the DOM
👉 JSX
:
a syntax that combines
HTML, CSS, JavaScript, as well as
referencing other components
JSX returned from a component
Based on components
Declarative
Extremely popular
JavaScript library
State-driven
Created by facebook
REACT IS STATE
-
DRIVEN
UI
1 RENDER
3 UPDATE STATE
4 RE
-
RENDER
Components
written with JSX
Search apartments
2
REACT REACTS TO STATE CHANGES
BY RE
-
RENDERING THE UI
STATE
Example: array
of apartments
Based on components
State-driven
Declarative
Extremely popular
JavaScript library
Created by facebook
REACT IS A JAVASCRIPT LIBRARY
🤔 Is React a library or a framework?
JavaScript library
Based on components
State-driven
Declarative
Extremely popular
Created by facebook
Because React is only the “view” layer. We
need to pick multiple external libraries to
build a complete application
Complete frameworks built on top of React
REACT IS EXTREMELY POPULAR
(
Weekly downloads from NPM
)
✅ Many large companies have adopted React
✅ Huge job market with high demand for React developers 🤑
✅ Large and vibrant React developer community
✅ Gigantic third-party library ecosystem
React is extremely
popular
Extremely popular
JavaScript library
Based on components
State-driven
Declarative
Created by facebook
REACT WAS CREATED BY FACEBOOK
Extremely popular
JavaScript library
Based on components
State-driven
Declarative
Created by facebook
👉 React was created in 2011 by Jordan Walke, an
engineer working at Facebook at the time
👉 React was open-sourced in 2013, and has since
then completely transformed front-end web
development
🎯 SUMMARY
1 Rendering components on a webpage
(
UI
)
based on their current state
2 Keeping the UI in sync with state, by re-rendering (reacting) when state changes
Component 3
Component 1
Component 2
RENDER
RE
-
RENDER
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
A FIRST LOOK AT REACT
SETTING UP A NEW REACT
PROJECT
:
THE TWO OPTIONS
THE TWO OPTIONS FOR SETTING UP A RECT PROJECT
👉 Complete “starter kit” for React applications
👍 Everything is already configured: ESLint,
Prettier, Jest, etc.
👎 Uses slow and outdated technologies (i.e.
webpack)
👉 Modern build tool that contains a template
for setting up React applications
👎 Need to manually set up ESLint (and others)
👍 Extremely fast hot module replacement
(
HMR
)
and bundling
VITE
CREATE
-
REACT
-
APP
✅ Use for tutorials or experiments
⛔ Don’t use for a real-world app
✅ Use for modern real-world apps
By the end of the course
Most of the course
Jest
WHAT ABOUT REACT FRAMEWORKS?
👉 The React team now advises to use a “React
Framework” for new projects
👉 Many people think that this is not the best
idea: “vanilla” React apps are important too!
👉 This only makes sense for building actual
products, not for learning React
👉 Of course, you still need to learn React itself
✌ Don’t worry about this recommendation
for now. Let’s just learn React!
👉 react.dev
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
WORKING WITH
COMPONENTS,
PROPS, AND JSX
SECTION
LECTURE
WORKING WITH COMPONENTS,
PROPS, AND JSX
COMPONENTS AS BUILDING
BLOCKS
COMPONENTS AS BUILDING BLOCKS
COMPONENTS
👉 React applications are entirely made out of
components
👉 Building blocks of user interfaces in React
COMPONENTS AS BUILDING BLOCKS
COMPONENTS
Webpage
(
UI
)
Component A
Component B
Component B
Component C
Component A
Data Appearance
Logic
👉 React applications are entirely made out of
components
👉 Building blocks of user interfaces in React
👉 Piece of UI that has its own data, logic,
and appearance (how it works and looks)
👉 We build complex UIs by building multiple
components and combining them
COMPONENTS AS BUILDING BLOCKS
COMPONENTS
👉 React applications are entirely made out of
components
👉 Building blocks of user interfaces in React
👉 Piece of UI that has its own data, logic,
and appearance (how it works and looks)
👉 We build complex UIs by building multiple
components and combining them
👉 Components can be reused, nested inside
each other, and pass data between them
VideoPlayer
QuestionList
Question
Question
Question
RefineQuestions
Filters
Menu
COMPONENT TREES
App
Questions
List
Video
Player
Menu
Refine
Questions
Question
Question
Question
Filters
VideoPlayer
QuestionList
Question
Question
Question
RefineQuestions
Filters
Menu
Parent
component
Child
component
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
WORKING WITH COMPONENTS,
PROPS, AND JSX
WHAT IS JSX?
Component
Data
Appearance
Logic
WHAT IS JSX?
JSX
👉 Declarative syntax to describe what
components look like and how they work
👉 Components must return a block of JSX
👉 Extension of JavaScript that allows us to
embed JavaScript, CSS, and React
components into HTML
Appearance
JSX returned from component
WHAT IS JSX?
JSX
👉 Declarative syntax to describe what
components look like and how they work
👉 Components must return a block of JSX
👉 Extension of JavaScript that allows us to
embed JavaScript, CSS, and React
components into HTML
👉 Each JSX element is converted to a
React.createElement function call
👉 We could use React without JSX
JSX IS DECLARATIVE
IMPERATIVE
DECLARATIVE
👉 Manual DOM element selections and DOM traversing
👉 Step-by-step DOM mutations until we reach the desired UI
👉 Describe what UI should look like using JSX, based on current data
👉 React is an abstraction away from DOM
:
we never touch the DOM
👉 Instead, we think of the UI as a reflection of the current data
“How to do things”
“What we want”
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
WORKING WITH COMPONENTS,
PROPS, AND JSX
SEPARATION OF CONCERNS
SEPARATION OF CONCERNS?
ONE TECHNOLOGY PER FILE
Rise of
interactive
SPAs
Logic and UI are
tightly coupled
JavaScript is in
charge of HTML
Why keep them
separated?
React
Components
+
JSX
“Traditional” separation
of concerns
SEPARATION OF CONCERNS?
ONE COMPONENT PER FILE
Rise of
interactive
SPAs
Logic and UI are
tightly coupled
JavaScript is in
charge of HTML
Why keep them
separated?
React
Components
+
JSX
HTML and JS
are colocated
Component
Data
Appearance
Logic
Fundamental reason for components
SEPARATION OF CONCERNS!
ONE TECHNOLOGY PER FILE
Rise of
interactive
SPAs
Logic and UI are
tightly coupled
JavaScript is in
charge of HTML
Why keep them
separated?
React
Components
+
JSX
ONE COMPONENT PER FILE
Question
Menu
Filters
Player
“Traditional”
separation of
concerns
COMPLETELY
NEW PARADIGM
Each component
is concerned
with one piece
of the UI
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
WORKING WITH COMPONENTS,
PROPS, AND JSX
PROPS, IMMUTABILITY, AND ONE
-
WAY DATA FLOW
Header Menu Footer
App
Pizza Order
Pizza
Pizza
REVIEWING PROPS
PROPS
👉 Props are used to pass data from parent
components to child components (down
the component tree)
REVIEWING PROPS
PROPS
👉 Props are used to pass data from parent
components to child components (down
the component tree)
👉 Essential tool to configure and customize
components (like function parameters)
👉 With props, parent components control
how child components look and work
REVIEWING PROPS
PROPS
👉 Props are used to pass data from parent
components to child components (down
the component tree)
👉 Essential tool to configure and customize
components (like function parameters)
👉 With props, parent components control
how child components look and work
👉 Anything can be passed as props: single
values, arrays, objects, functions, even
other components
PROPS ARE READ
-
ONLY!
Data
Appearance
Logic
Component
Props
State
Data
Appearance
Logic
State is internal data that can be
updated by the component’s logic
Parent
Component
Props is data coming from the
outside, and can only be updated by
the parent component
☝ Props are read-only, they are
immutable! This is one of
React’s strict rules.
☝ If you need to mutate props,
you actually need state
👉 Mutating props would affect parent,
creating side effects (not pure)
👉 Components have to be pure
functions in terms of props and state
👉 This allows React to optimize apps,
avoid bugs, make apps predictable
WHY?
Don’t do this!
ONE
-
WAY DATA FLOW
App
Pizza
Pizza
Pizza Order
Header Menu Footer
ONE
-
WAY DATA FLOW...
👍 ... makes applications more
predictable and easier to
understand
👍 … makes applications
easier to debug, as we have
more control over the data
👍 … is more performant
Angular has two-way data flow
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
WORKING WITH COMPONENTS,
PROPS, AND JSX
THE RULES OF JSX
DIFFERENCES BETWEEN JSX AND HTML
RULES OF JSX
👉 className instead of HTML’s class
👉 htmlFor instead of HTML’s for
👉 Every tag needs to be closed. Examples: <img />
or <br />
👉 All event handlers and other properties need to be
camelCased. Examples: onClick or onMouseOver
👉 Exception: aria-* and data-* are written with
dashes like in HTML
👉 CSS inline styles are written like this: {{<style>}}
(to reference a variable, and then an object)
👉 CSS property names are also camelCased
👉 Comments need to be in {} (because they are JS
)
GENERAL JSX RULES
👉 JSX works essentially like HTML, but we can enter
“JavaScript mode” by using {} (for text or attributes)
👉 We can place JavaScript expressions inside {}.
Examples: reference variables, create arrays or objects,
[].map(), ternary operator
👉 Statements are not allowed (if/else, for, switch)
👉 JSX produces a JavaScript expression
1⃣ We can place other pieces of JSX inside {}
2⃣ We can write JSX anywhere inside a component (in
if/else, assign to variables, pass it into functions)
==
👉 A piece of JSX can only have one root element. If you
need more, use <React.Fragment> (or the short <>)
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
WORKING WITH COMPONENTS,
PROPS, AND JSX
SECTION SUMMARY
App
Pizza
Pizza
Pizza Order
Header Menu Footer
🎯 SECTION SUMMARY
Component
Data
Appearance: JSX
JS Logic
To pass data from parent
to child components
Props
List of
Pizzas
Rendering multiple
components at once
using the JavaScript
.map() method
Components in
component tree
“HTML”
CSS
JS inside {}
JSX block is what
we return from a
component
Components can be
conditionally rendered
using JS tools: &&, ?,
and multiple return
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
STATE, EVENTS, AND
FORMS
:
INTERACTIVE
COMPONENTS
SECTION
LECTURE
STATE, EVENTS, AND FORMS
:
INTERACTIVE COMPONENTS
WHAT IS STATE IN REACT?
Rest of the
course...
What is state and why do we need it?
1
2 How to use state in practice?
👉 useState
👉 useReducer
👉 Context API
3 Thinking about state
👉 When to use state
👉 Where to place state
👉 Types of state
📚 WHAT WE NEED TO LEARN
WHAT REACT DEVELOPERS NEED TO LEARN ABOUT STATE
:
👋 State is the most important
concept in React
(
So we will keep learning about state
throughout the entire course…)
This section
Data
Appearance
Logic
Component
Props
Data
WHAT IS STATE?
STATE
👉 Data that a component can hold over time,
necessary for information that it needs to
remember throughout the app’s lifecycle
State
Parent
Component
👉 “Component’s memory”
🧠
WHAT IS STATE?
STATE
👉 Data that a component can hold over time,
necessary for information that it needs to
remember throughout the app’s lifecycle
👉 “Component’s memory”
🧠
👉 “State variable” / “piece of state”
:
A single
variable in a component (component state)
We use these terms
interchangeably
WHAT IS STATE?
STATE
👉 Data that a component can hold over time,
necessary for information that it needs to
remember throughout the app’s lifecycle
👉 Updating component state triggers React
to re-render the component
Data
Appearance
Logic
Component
Props
Data
State
Parent
Component
👉 “Component’s memory”
🧠
Component
rendered in the UI
Component
View
👉 Component state: Single local component
variable (“Piece of state”, “state variable”)
DATA UI
State
WHAT IS STATE?
STATE
1
Update the component’s
view (by re-rendering it)
2
Persist local variables between
renders
STATE ALLOWS DEVELOPERS TO
:
👋 State is a tool. Mastering state will
unlock the power of React development
👉 Data that a component can hold over time,
necessary for information that it needs to
remember throughout the app’s lifecycle
👉 Updating component state triggers React
to re-render the component
👉 “Component’s memory”
🧠
👉 Component state: Single local component
variable (“Piece of state”, “state variable”)
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
STATE, EVENTS, AND FORMS
:
INTERACTIVE COMPONENTS
THE MECHANICS OF STATE
THE MECHANICS OF STATE IN REACT
We don’t do
direct DOM
manipulations
How is a
component view
updated then?
In React, a view
is updated by
re-rendering the
component
Because React
is declarative
VIEW
RENDER /
RE
-
RENDER
UPDATED
VIEW
A component is
re-rendered
when its state is
updated
STATE
Important
React principle
👉 State is preserved
throughout re-renders
React calls the
component
function again
We don’t do
direct DOM
manipulations
How is a
component view
updated then?
In React, a view
is updated by
re-rendering the
component
A component is
re-rendered
when its state is
updated
VIEW
3 RE
-
RENDER
RENDER /
RE
-
RENDER
STATE
UPDATED
VIEW
Event handler
1
UPDATED
STATE
UPDATE STATE
2
THE MECHANICS OF STATE IN REACT
We don’t do
direct DOM
manipulations
In React, a view
is updated by
re-rendering the
component
How is a
component view
updated then?
A component is
re-rendered
when its state is
updated
RE
-
RENDER
UPDATE STATE
THE MECHANICS OF STATE IN REACT
So to update a
view, we update
state
We don’t do
direct DOM
manipulations
In React, a view
is updated by
re-rendering the
component
How is a
component view
updated then?
A component is
re-rendered
when its state is
updated
THE MECHANICS OF STATE IN REACT
So to update a
view, we update
state
REACT REACTS TO STATE CHANGES
BY RE
-
RENDERING THE UI
👉 React is called “React” because...
DATA UI
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
STATE, EVENTS, AND FORMS
:
INTERACTIVE COMPONENTS
MORE THOUGHTS ABOUT STATE
+
STATE GUIDELINES
0
ONE COMPONENT, ONE STATE
Counter
Multiple instances of the
Counter component
Counter Counter
TeamScores
score = 0 score = 0 score = 0
0
0
1
2
score = 1
score = 2 score = 1
1
👋 Each component has and manages its
own state, no matter how many times
we render the same component
DECLARATIVE, REVISITED
UI AS A FUNCTION OF STATE
UI =
TIME
STATE
UI
👉 With state, we view UI as a reflection of data changing over time
👉 We describe that reflection of data using state, event handlers, and JSX
f(state )
Component A
Component D
Component B
Component C
🎯 IN PRACTICAL TERMS...
👉 Example: A modal window can be open or closed. So we create a state variable
isOpen that tracks whether the modal is open or not. On isOpen = true we
display the window, on isOpen = false we hide it.
👉 If you want to change the way a component looks, or the data it displays, update its state.
This usually happens in an event handler function.
👉 Whenever you want something in the component to be dynamic, create a piece of state related
to that “thing”, and update the state when the “thing” should change (aka “be dynamic”)
👉 Use a state variable for any data that the component should keep track of (“remember”) over
time. This is data that will change at some point. In Vanilla JS, that’s a let variable, or an [] or {}
👉 For data that should not trigger component re-renders, don’t use state. Use a regular variable
instead. This is a common beginner mistake.
PRACTICAL GUIDELINES ABOUT STATE
👉 When building a component, imagine its view as a reflection of state changing over time
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
STATE, EVENTS, AND FORMS
:
INTERACTIVE COMPONENTS
STATE VS. PROPS
STATE VS. PROPS
STATE PROPS
👉 Internal data, owned by
component
👉 Component “memory”
👉 Can be updated by the
component itself
👉 Updating state causes
component to re-render
👉 Used to make components
interactive
👉 External data, owned by
parent component
👉 Similar to function parameters
👉 Read-only
👉 Receiving new props causes
component to re-render.
Usually when the parent’s
state has been updated
👉 Used by parent to configure
child component (“settings”)
Parent state
update
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
THINKING IN REACT
:
STATE MANAGEMENT
SECTION
LECTURE
THINKING IN REACT
:
STATE
MANAGEMENT
WHAT IS "THINKING IN REACT"?
THINKING IN REACT
“THINKING IN REACT” IS A CORE SKILL
HOW TO
WORK WITH
REACT API
THINKING IN
REACT
This is where professional
React apps are built
👉 “React Mindset”
👉 Thinking about components,
state, data flow, effects, etc.
👉 Thinking in state transitions, not
element mutations
State
management
WHEN YOU KNOW HOW TO “THINK IN
REACT”, YOU WILL BE ABLE TO ANSWER
:
“THINKING IN REACT” AS A PROCESS
🤔 How to break up a UI design into components?
🤔 How to make some components reusable?
🤔 How to assemble UI from reusable components?
🤔 What pieces of state do I need for interactivity?
🤔 Where to place state?
(
What component should
"own" each piece of state?
)
🤔 What types of state can or should I use?
🤔 How to make data flow through app?
Break the desired UI into components and
establish the component tree
1
THE “THINKING IN REACT” PROCESS
:
2 Build a static version in React (without state)
👉 When to use state
👉 Types of state: local vs. global
👉 Where to place each piece of state
3 Think about state:
4 Establish data flow:
👉 One-way data flow
👉 Child-to-parent communication
👉 Accessing global state
Not a rigid process
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
THINKING IN REACT
:
STATE
MANAGEMENT
FUNDAMENTALS OF STATE
MANAGEMENT
WHAT IS STATE MANAGEMENT?
language
searchQuery
shoppingCart
user
isOpen
coupons
notifications
👉 State management: Deciding when to create pieces of
state, what types of state are necessary, where to place
each piece of state, and how data flows through the app
🏠 Giving each piece
of state a home
PIECES OF
STATE
(useState)
TYPES OF STATE
:
LOCAL VS. GLOBAL STATE
LOCAL STATE GLOBAL STATE
Context API
👉 State needed only by one or few components
👉 State that is defined in a component and only
that component and child components have
access to it (by passing via props)
☝ We should always start with local state
👉 State that many components might need
👉 Shared state that is accessible to every
component in the entire application
Global state
Local state
STATE
:
WHEN AND WHERE?
Need to store data Will data change at some point?
Only used by this component?
WHERE TO PLACE STATE
WHEN TO CREATE STATE
Can be computed from existing state/props?
YES
Regular const variable
NO
Should it re-render component?
NO
Place a new piece of state in component
YES
Derive state
YES
Ref (useRef, more on this later)
NO
Also used by a child component?
NO
Used by one or a few sibling components?
NO
👉 Probably global state. Global state
management later in the course...
NO
Leave in component
YES
Pass to child via props
YES
Lift state up to first common parent
YES
“Always start
with local state”
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
THINKING IN REACT
:
STATE
MANAGEMENT
REVIEWING "LIFTING UP STATE"
PROBLEM
:
SHARING STATE WITH SIBLING COMPONENT
Total
Checkout Total
Promotions
coupons
ONE
-
WAY
DATA FLOW
🤔 How do we share state with other components?
coupons
👉 Total component also needs
access to coupons state
Promotions
coupons
setCoupons
Data can only flow down to children
(via props), not sideways to siblings
coupons
SOLUTION
:
LIFTING STATE UP
Promotions
Total
Checkout Total
coupons
coupons
ONE
-
WAY
DATA FLOW coupons
coupons
setCoupons
props props
Promotions
coupons
✌ By lifting state up, we have successfully shared one
piece of state with multiple components in different
positions in the component tree
State was lifted up to the
closest common parent
👉 Total component also needs
access to coupons state
CHILD
-
TO
-
PARENT COMMUNICATION
Promotions
Total
Checkout Total
coupons
coupons
👉 Total component also needs
access to coupons state
ONE
-
WAY
DATA FLOW
coupons
coupons
props props
Promotions
coupons
🤔 If data flows from parent to children, how can
Promotions (child) update state in Checkout (parent)?
setCoupons
setCoupons UPDATE
👉 Child-to-parent communication (inverse data
flow): child updating parent state (data “flowing” up)
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
THINKING IN REACT
:
STATE
MANAGEMENT
DERIVED STATE
DERIVING STATE
DERIVING STATE
👎 Three separate pieces of state, even though
numItems and totalPrice depend on cart
👎 Need to keep them in sync (update together)
👎 3 state updates will cause 3 re-renders
👍 Derived state: state that is computed from
an existing piece of state or from props
👍 Just regular variables, no useState
👍 cart state is the single source of truth for
this related data
👍 Works because re-rendering component will
automatically re-calculate derived state
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
THINKING IN REACT
:
STATE
MANAGEMENT
THE CHILDREN PROP
:
MAKING A
REUSABLE BUTTON
Children of Button,
accessible through
props.children
THE CHILDREN PROP
Button
👉 The children prop allow us to pass JSX into an element (besides regular props)
👉 Essential tool to make reusable and configurable components (especially component content)
👉 Really useful for generic components that don’t know their content before being used (e.g. modal)
props.children
An empty “hole” that can be filled
by any JSX the component
receives as children
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
PART 02
—
INTERMEDIATE
REACT
THINKING IN REACT
:
COMPONENTS,
COMPOSITION, AND
REUSABILITY
SECTION
LECTURE
THINKING IN REACT
:
COMPONENTS, COMPOSITION,
AND REUSABILITY
HOW TO SPLIT A UI INTO
COMPONENTS
COMPONENT SIZE MATTERS
COMPONENT SIZE
👉 Too many responsibilities
👉 Might need too many props
👉 Hard to reuse
👉 Complex code, hard to understand
SMALL HUGE
Just one huge
component
COMPONENT SIZE MATTERS
COMPONENT SIZE
👉 We end up with 100s of mini-components
👉 Confusing codebase
👉 Too abstracted
SMALL HUGE
0
0
0
Many small
components
Generally, we need to find the right balance
between too specific and too broad
👉 Too many responsibilities
👉 Might need too many props
👉 Hard to reuse
👉 Complex code, hard to understand
Creating something new to hide the
implementation details of that thing
HOW TO SPLIT A UI INTO COMPONENTS
0
0
0
0
0
3. Responsibilities
/ complexity
2. Reusability
4. Personal
coding style
1.Logical separation
of content/layout
👉 The 4 criteria for splitting
a UI into components:
✅ Logical separation
✅ Some are reusable
✅ Low complexity
👎
👎
FRAMEWORK
:
WHEN TO CREATE A NEW COMPONENT?
👉 Is it possible to reuse part of the component?
👉 Do you want or need to reuse it?
👉 Is the component doing too many different things?
👉 Does the component rely on too many props?
👉 Does the component have too many pieces of state
and/or effects?
👉 Is the code, including JSX, too complex/confusing?
👉 Do you prefer smaller functions/components?
💡 SUGGESTION
:
When in doubt, start with a relatively big component,
then split it into smaller components as it becomes necessary
You might
need a new
component
Skip if you're sure you
need to reuse. But
otherwise, you don’t need
to focus on reusability
and complexity early on
3. Responsibilities
/ complexity
2. Reusability
4. Personal
coding style
👉 Does the component contain pieces of content or layout
that don’t belong together?
1.Logical separation
of content/layout
👋 These are all
guidelines… It will
become intuitive
over time!
SOME MORE GENERAL GUIDELINES
💰 Be aware that creating a new component creates a new abstraction. Abstractions
have a cost, because more abstractions require more mental energy to switch back
and forth between components. So try not to create new components too early
🏷 Name a component according to what it does or what it displays. Don’t be afraid of
using long component names
🪆 Never declare a new component inside another component!
🗃 Co-locate related components inside the same file. Don’t separate components into
different files too early
↔ It’s completely normal that an app has components of many different sizes, including
very small and huge ones
(
See next slide... 👉)
0
0
ANY APP HAS COMPONENTS OF DIFFERENT SIZES AND REUSABILITY
SMALL HUGE
Components with all different sizes
👉 Some very small components are necessary!
👉 Highly reusable
👉 Very low complexity
👉 Most apps will have a few huge components
👉 Not meant to be reused (not a problem!
)
👉 Page component
REUSABLE
NON
-
REUSABLE
Different degrees of size, reusability,
responsibility, and complexity
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
THINKING IN REACT
:
COMPONENTS, COMPOSITION,
AND REUSABILITY
COMPONENT CATEGORIES
COMPONENT CATEGORIES
👉 Most of your components will naturally fall into one of three categories:
Stateful
components
Stateless /
presentational
components
Structural
components
👉 No state
👉 Can receive props and
simply present received
data or other content
👉 Usually small and reusable
👉 Have state
👉 Can still be reusable
👉 “Pages”, “layouts”, or
“screens” of the app
👉 Result of composition
👉 Can be huge and non-
reusable (but don’t have to)
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
THINKING IN REACT
:
COMPONENTS, COMPOSITION,
AND REUSABILITY
COMPONENT COMPOSITION
“USING” A COMPONENT
WHAT IS COMPONENT COMPOSITION?
Modal
COMPONENT COMPOSITION
👉 Success is inside Modal: we can NOT
reuse Modal
Modal
Success
👉 Success is passed into Modal: we
can REUSE Modal
Success
Want to
reuse
WHAT IS COMPONENT COMPOSITION?
COMPONENT COMPOSITION
Modal Error
👉 Success is passed into Modal: we
can REUSE Modal
👉 Component composition: combining
different components using the
children prop (or explicitly defined
props)
Create highly reusable and flexible
components
1
2 Fix prop drilling (great for layouts)
WE COMPONENT COMPOSITION, WE CAN
:
Possible because components don’t
need to know their children in advance
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
THINKING IN REACT
:
COMPONENTS, COMPOSITION,
AND REUSABILITY
PROPS AS A COMPONENT API
TOO LITTLE PROPS
PROPS AS AN API
👉 Too hard to use
👉 Exposing too much complexity
👉 Hard-to-write code
👉 Provide good default values
👉 Not flexible enough
👉 Might not be useful
TOO MANY PROPS
👩💻
COMPONENT
CONSUMER
🧑💻
COMPONENT
CREATOR
We need to find the right
balance between too little
and too many props, that
works for both the
consumer and the creator
🎛
Component props
=
Public API
Consuming
component
App
👩💻
Component
Abstraction that
encapsulates UI and logic
GOT QUESTIONS? FEEDBACK?
JUST POST IT IN THE Q&A OF
THIS VIDEO, AND YOU WILL
GET HELP THERE!
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
HOW REACT WORKS
BEHIND THE SCENES
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
COMPONENTS, INSTANCES, AND
ELEMENTS
COMPONENT VS. INSTANCE VS. ELEMENT
Component
👉 Description of a piece of UI
👉 A component is a function that returns React
elements (element tree), usually written as JSX
👉 “Blueprint” or “Template”
COMPONENT VS. INSTANCE VS. ELEMENT
Component
Component Instance
👉 Instances are created when we “use” components
👉 React internally calls Tab()
👉 Actual “physical” manifestation of a component
👉 Has its own state and props
👉 Has a lifecycle (can “be born”, “live”, and “die”)
Instances of Tab
COMPONENT VS. INSTANCE VS. ELEMENT
Component
Component Instance
React Element
RETURNS
👉 JSX is converted to React.createElement() function calls
👉 A React element is the result of these function calls
👉 Information necessary to create DOM elements
REACT ELEMENT
COMPONENT VS. INSTANCE VS. ELEMENT
Component
Component Instance
React Element
RETURNS
DOM Element
(
HTML
)
INSERTED TO DOM
👉 Actual visual representation of the component
instance in the browser
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
HOW RENDERING WORKS
:
OVERVIEW
QUICK RECAP BEFORE WE GET STARTED
User
Interface on
the screen
Component A
Component B
React
Element
React
Element
React
Element
React
Element
DOM Element
(
HTML
)
DOM Element
(
HTML
)
DOM Element
(
HTML
)
DOM Element
(
HTML
)
Component
Instance A2
Component
Instance A1
Component
Instance A3
.
.
.
Component
Instance B1
.
.
.
🤔 How does this process actually work?
OVERVIEW
:
HOW COMPONENTS ARE DISPLAYED ON THE SCREEN
RENDER IS
TRIGGERED
RENDER
PHASE
COMMIT
PHASE
BROWSER
PAINT
☝ In React, rendering is NOT updating the DOM or displaying elements on the screen.
Rendering only happens internally inside React, it does not produce visual changes.
Common sense meaning of the word “render”
By updating
state somewhere
React calls component
functions and figures out how
DOM should be updated
React actually writes to the
DOM, updating, inserting, and
deleting elements
THE TWO SITUATIONS THAT TRIGGER RENDERS
:
HOW RENDERS ARE TRIGGERED
[
1
]
RENDER IS TRIGGERED
👉 In practice, it looks like React only re-renders the component where the state update
happens, but that’s not how it works behind the scenes
👉 Renders are not triggered immediately, but scheduled for when the JS engine has
some “free time”. There is also batching of multiple setState calls in event handlers
Initial render of the application
1
2 State is updated in one or more component instances (re-render)
👉 The render process is triggered for the entire application
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
HOW RENDERING WORKS
:
THE
RENDER PHASE
VIEW
3 RE
-
RENDER
RENDER /
RE
-
RENDER
STATE
UPDATED
VIEW
Event handler
1
UPDATED
STATE
UPDATE STATE
2
REVIEW
:
THE MECHANICS OF STATE IN REACT
NOT TRUE #1
:
RENDERING IS UPDATING THE SCREEN / DOM
NOT TRUE #2
:
REACT COMPLETELY DISCARDS OLD VIEW
(
DOM
)
ON RE
-
RENDER
THE RENDER PHASE
[
2
]
RENDER PHASE
Component
instances that
triggered re-render
New
Virtual DOM
React Elements
C
COMPONENT TREE
B
A
D
E E
C
COMPONENT TREE
B
A
E E
D
STATE
UPDATE
C
REACT ELEMENT TREE
B
A
D
E E
THE VIRTUAL DOM
(
REACT ELEMENT TREE
)
1⃣ INITIAL RENDER
C
REACT ELEMENT TREE
B
A
D
E E
D
E E
“Virtual DOM”
👉 Virtual DOM
:
Tree of all React
elements created from all
instances in the component tree
👉 Cheap and fast to create multiple
trees
👉 Nothing to do with “shadow DOM”
🔄 RE
-
RENDERS
🚨 Rendering a component will
cause all of its child components
to be rendered as well (no matter
if props changed or not)
C
COMPONENT TREE
B
A
D
E E
C
COMPONENT TREE
B
A
E E
D
STATE
UPDATE
C
REACT ELEMENT TREE
B
A
D
E E
THE VIRTUAL DOM
(
REACT ELEMENT TREE
)
1⃣ INITIAL RENDER
C
REACT ELEMENT TREE
B
A
D
E E
A
“Virtual DOM”
👉 Virtual DOM
:
Tree of all React
elements created from all
instances in the component tree
👉 Cheap and fast to create multiple
trees
👉 Nothing to do with “shadow DOM”
🔄 RE
-
RENDERS
🚨 Rendering a component will
cause all of its child components
to be rendered as well (no matter
if props changed or not)
👉
Necessary because React doesn’t
know whether children will be
affected
THE RENDER PHASE
[
2
]
RENDER PHASE
Component
instances that
triggered re-render
New
Virtual DOM
Current
Fiber tree
(before state update)
Updated
Fiber tree
React Elements
Reconciler
called “Fiber”
Reconciliation
+
Diffing
WHAT IS RECONCILIATION AND WHY DO WE NEED IT?
🤔 Why not update the entire DOM whenever state
changes somewhere in the app?
showModal = true
👉 That would be inefficient and wasteful:
👉 React reuses as much of the existing DOM as possible
❤ Reconciliation: Deciding which DOM elements
actually need to be inserted, deleted, or updated,
in order to reflect the latest state changes
Writing to the DOM is (relatively) slow
1
2
Usually only a small part of the DOM needs
to be updated
BECAUSE
HOW?
Only these new DOM elements are created
Current state
Props
Side effects
Used hooks
FIBER
Modal
Video Btn
Overlay
h3 button
App
FIBER
TREE
ON INITIAL
RENDER
THE RECONCILER
:
FIBER
REACT
ELEMENT
TREE
(
VIRTUAL
DOM
)
Modal
Video Btn
App
Overlay
h3 button
👉 Fiber tree: internal tree that has a
“fiber” for each component
instance and DOM element
👉 Fibers are NOT re-created on
every render
👉 Work can be done asynchronously Queue of work
“Unit of work”
👉 Rendering process can be split into
chunks, tasks can be prioritized, and work
can be paused, reused, or thrown away
👉 Enables concurrent features like
Suspense or transitions
👉 Long renders won’t block JS engine
UPDATED FIBER TREE
Modal
Video Btn
Overlay
h3 button
App
(
Showing DOM work)
App
Video Btn
NEW VIRTUAL
DOM
RECONCILIATION IN ACTION
Modal
Video Btn
App
Overlay
h3 button
showModal = true
Modal
Video Btn
Overlay
h3 button
App
CURRENT FIBER TREE
showModal = false
STATE
UPDATE
DOM
Deletions
DOM
Update
(text)
State update in App, so
all remaining children
are re-rendered
Reconciliation
+
Diffing
(workInProgress)
Comparing elements based
on their position in the tree
THE RENDER PHASE
[
2
]
RENDER PHASE
Component
instances that
triggered re-render
New
Virtual DOM
Updated
Fiber tree
List of DOM
updates
React Elements
Result of the
render phase
(“list of effects”)
Reconciler
called “Fiber”
Reconciliation
+
Diffing
Current
Fiber tree
(before state update)
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
HOW RENDERING WORKS
:
THE
COMMIT PHASE
THE COMMIT PHASE AND BROWSER PAINT
[
3
]
COMMIT PHASE
[
4
]
BROWSER PAINT
Updated DOM
List of DOM
updates
[
2
]
RENDER PHASE
Updated UI on the
screen
React React
👉 React writes to the DOM
:
insertions, deletions, and updates (list of
DOM updates are “flushed” to the DOM
)
👉 Committing is synchronous: DOM is updated in one go, it can’t be
interrupted. This is necessary so that the DOM never shows partial
results, ensuring a consistent UI (in sync with state at all times)
👉 After the commit phase completes, the workInProgress fiber tree
becomes the current tree for the next render cycle
DOM
THE COMMIT PHASE AND BROWSER PAINT
[
3
]
COMMIT PHASE
[
4
]
BROWSER PAINT
Updated DOM
Updated UI on the
screen
React ReactDOM
Does not touch the DOM.
React only renders. It
doesn’t know where the
render result will go
React Native
Many others…
React can be used on
different platforms (“hosts”)
“RENDERERS”
Terrible name! Renderers do not render, they commit the result of render phase…
List of DOM
updates
[
2
]
RENDER PHASE
[
4
]
BROWSER
PAINT
[
3
]
COMMIT
PHASE
[
2
]
RENDER PHASE
RECAP
:
PUTTING IT ALL TOGETHER
List of DOM
updates
Updated UI on
screen
Updated
Fiber tree
Current
Fiber tree
Reconciliation
+
Diffing
[
1
]
TRIGGER 💥
Updated DOM
New
Virtual DOM
Updated React
Elements
👉 Does not produce any visual output
👉 Rendering a component also renders all of its child components
👉 Asynchronous: work can be split, prioritized, paused, resumed
👉 Happens only on initial render and state updates
👉 Synchronous: DOM updates are written in one go, to keep UI consistent
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
HOW DIFFING WORKS
THE RENDER PHASE
[
2
]
RENDER PHASE
Component
instances that
triggered re-render
New
Virtual DOM
Updated
Fiber tree
List of DOM
updates
React Elements
Reconciliation
+
Diffing
Current
Fiber tree
(before state update)
Comparing elements step-
by-step, based on their
position in the tree
HOW DIFFING WORKS
👉 Diffing uses 2 fundamental
assumptions (rules):
Two elements of
different types will
produce different trees
1
2
Elements with a stable
key prop stay the
same across renders
👉 This allows React to go from
1,000,000,000
[
O(n3)] to
1000 [O(n)] operations per
1000 elements
1. SAME POSITION, DIFFERENT ELEMENT
👉 React assumes entire sub-tree is no longer valid
👉 Old components are destroyed and removed from DOM, including state
👉 Tree might be rebuilt if children stayed the same (state is reset)
Different
DOM element
Different React
element (component
instance)
HOW DIFFING WORKS
2. SAME POSITION, SAME ELEMENT
👉 Diffing uses 2 fundamental
assumptions (rules):
Two elements of
different types will
produce different trees
1
2
Elements with a stable
key prop stay the
same across renders
👉 Element will be kept (as well as child elements), including state
👉 New props / attributes are passed if they changed between renders
👉 Sometimes this is not what we want… Then we can use the key prop
Same DOM
element
Same React
element
(component
instance)
👉 This allows React to go from
1,000,000,000
[
O(n3)] to
1000 [O(n)] operations per
1000 elements
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
THE KEY PROP
WHAT IS THE KEY PROP?
KEY PROP
👉 Special prop that we use to tell the diffing algorithm that an element is unique
👉 Allows React to distinguish between multiple instances of the same component type
👉 When a key stays the same across renders, the element will be kept in the DOM
(even if the position in the tree changes)
👉 When a key changes between renders, the element will be destroyed and a new one
will be created (even if the position in the tree is the same as before)
Using keys in lists
1
2 Using keys to reset state
👍 WITH KEYS
ADDING NEW LIST ITEM
ADDING NEW LIST ITEM
1. KEYS IN LISTS
[
STABLE KEY
]
👎 NO KEYS
👉 Same elements, but different position in
tree, so they are removed and recreated
in the DOM (bad for performance)
👉 Different position in the tree, but the key
stays the same, so the elements will be
kept in the DOM 👉 Always use keys!
2. KEY PROP TO RESET STATE
[
CHANGING KEY
]
👉 If we have the same element at the same position in
the tree, the DOM element and state will be kept
Question state (answer):
State was
preserved. NOT
what we want
Question state (answer):
NEW QUESTION IN
SAME POSITION
2. KEY PROP TO RESET STATE
[
CHANGING KEY
]
👉 If we have the same element at the same position in
the tree, the DOM element and state will be kept
Question state (answer):
NEW QUESTION IN
SAME POSITION
Question state (answer):
State was
RESET
👍 WITH KEY
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
RULES FOR RENDER LOGIC
:
PURE
COMPONENTS
2. EVENT HANDLER FUNCTIONS
THE TWO TYPES OF LOGIC IN REACT COMPONENTS
1. RENDER LOGIC
👉 Code that lives at the top level of the component function
👉 Participates in describing how the component view looks like
👉 Executed every time the component renders
👉 Executed as a consequence of the event that the handler is
listening for (change event in this example)
👉 Code that actually does things: update state, perform an HTTP
request, read an input field, navigate to another page, etc.
REFRESHER
:
FUNCTIONAL PROGRAMMING PRINCIPLES
👉 Side effect: dependency on or modification of any data
outside the function scope. “Interaction with the outside
world”. Examples: mutating external variables, HTTP
requests, writing to DOM.
👉 Pure function: a function that has no side effects.
👉 Does not change any variables outside its scope
👉 Given the same input, a pure function always
returns the same output
👋 Side effects are not bad! A program can only be
useful if it has some interaction with the outside world
✅ Pure function
☝ Impure function
☝ Impure function
Side effect: Outside
variable mutation
Unpredictable output
(date changes)
RULES FOR RENDER LOGIC
👋 Side effects are allowed (and encouraged) in event handler functions!
There is also a special hook to register side effects (useEffect)
☝ Components must be pure when it comes to render logic: given the same props
(input), a component instance should always return the same JSX (output)
☝ Render logic must produce no side effects: no interaction with the “outside
world” is allowed. So, in render logic:
👉 Do NOT perform network requests
(
API calls)
👉 Do NOT start timers
👉 Do NOT directly use the DOM API
👉 Do NOT mutate objects or variables outside of the function scope
👉 Do NOT update state (or refs): this will create an infinite loop!
This is why we can’t
mutate props!
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
STATE UPDATE BATCHING
HOW STATE UPDATES ARE BATCHED
👉 Renders are not triggered immediately, but scheduled for when the JS engine has
some “free time”. There is also batching of multiple setState calls in event handlers
Event
handler
function
HOW STATE UPDATES ARE BATCHED
answer = ''
NEW STATE
RENDER
+
COMMIT
best = true RENDER
+
COMMIT
solved = false RENDER
+
COMMIT
EVENT HANDLER FUNCTION
This is NOT how React updates
multiple pieces of state in the
same event handler
HOW STATE UPDATES ARE BATCHED
answer = ''
best = true
solved = false
NEW STATE
RENDER
+
COMMIT
EVENT HANDLER FUNCTION
Batched state update Just ONE render and
commit per event handler
No wasted renders,
better for performance
UPDATING STATE IS ASYNCHRONOUS
EVENT HANDLER FUNCTION
🤔
🤔 What will the value of answer be at this point?
State is stored in the Fiber tree during
render phase
At this point, re-render has not
happened yet
Therefore, answer still contains current
state, not the updated state ('')
UPDATING STATE IN REACT IS
ASYNCHRONOUS
👉 Updated state variables are not immediately available
after setState call, but only after the re-render
👉 This also applies when only one state variable is updated
👉 If we need to update state based on previous update, we
use setState with callback (setAnswer(answer=>...))
“Stale state”
BATCHING BEYOND EVENT HANDLER FUNCTIONS
EVENT HANDLERS
TIMEOUTS
PROMISES
NATIVE EVENTS
REACT 17 REACT 18
+
✅ ✅
✅
✅
✅
❌
❌
❌
👉 AUTOMATIC BATCHING IN...
👉 We can opt out of automatic
batching by wrapping a
state update in
ReactDOM.flushSync()
(but you will never need this)
We now get automatic batching
at all times, everywhere
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
HOW EVENTS WORK IN REACT
EVENT DELEGATION
DOM REFRESHER
:
EVENT PROPAGATION AND DELEGATION
DOCUMENT
<html>
<body>
<button>
.btn
<div>
.options
<header>
.topbar
<div>
#root
<button>
.btn
<button>
.btn
1
CAPTURING
PHASE
2 TARGET ELEMENT
3
BUBBLING
PHASE
DOM tree (not
Fiber tree or React
element tree)
👉 Handling events for multiple elements
centrally in one single parent element
👉 Better for performance and memory,
as it needs only one handler function
👋 Very common in vanilla JS apps,
but not so much in React apps
2 Check for target element (e.target)
3 If target is one of the <button>s,
handle the event
Add handler to parent (.options)
1
👉 By default, event
handlers listen to events
on the target and during
the bubbling phase
👉 We can prevent
bubbling with
e.stopPropagation()
H
H
EVENT
H H
DOCUMENT
<html>
<body>
<button>
.btn
<div>
.options
<header>
.topbar
<div>
#root
<button>
.btn
<button>
.btn
HOW REACT HANDLES EVENTS
WHEN WE ATTACH AN EVENT HANDLER...
👉 Behind the scenes, React performs event
delegation for all events in our applications
React registers all
event handlers on the
root DOM container.
This is where all
events are handled
Usually div#root, but
can be any DOM element
✅ ... WHAT ACTUALLY
HAPPENS INTERNALLY
⛔ ... WHAT APPEARS
TO BE HAPPENING
INSIDE REACT
FIBER TREE
H
H
SyntheticEvent
SYNTHETIC EVENTS
PointerEvent
MouseEvent
KeyboardEvent
...
👉 Wrapper around the DOM’s native event object
👉 Has same interface as native event objects, like
stopPropagation() and preventDefault()
👉 Fixes browser inconsistencies, so that events work
in the exact same way in all browsers
👉 Most synthetic events bubble (including focus,
blur, and change), except for scroll
👉 Attributes for event handlers are named using camelCase (onClick instead of onclick or click)
👉 Default behavior can not be prevented by returning false (only by using preventDefault())
👉 Attach “Capture” if you need to handle during capture phase (example: onClickCapture)
EVENT
HANDLERS IN
VS.
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
LIBRARIES VS. FRAMEWORKS &
THE REACT ECOSYSTEM
FIRST, AN ANALOGY 🍣
👍 Ease of mind: All ingredients are included
👎 No choice: You’re stuck with the kit’s ingredients
ALL
-
IN
-
ONE KIT SEPARATE INGREDIENTS
👍 Freedom: You can choose the best ingredients
👎 Decision fatigue: You need to research and buy
all ingredients separately
FIRST, AN ANALOGY 🍣
👍 Ease of mind: All ingredients are included
👎 No choice: You’re stuck with the kit’s ingredients
ALL
-
IN
-
ONE KIT SEPARATE INGREDIENTS
👍 Freedom: You can choose the best ingredients
👎 Decision fatigue: You need to research and buy
all ingredients separately
FRAMEWORK VS. LIBRARY
👍 Ease of mind: Everything you need to build a
complete application is included in the framework
(“batteries included”)
👎 No choice: You’re stuck with the framework’s tools
and conventions (which is not always bad!
)
FRAMEWORK LIBRARY
👍 Freedom: You can (or need to) choose multiple
3rd-party libraries to build a complete application
👎 Decision fatigue: You need to research,
download, learn, and stay up-to-date with
multiple external libraries
“Separate
ingredients”
“All-in-one kit”
Routing
HTTP requests Styling
Form management
LARGE
-
SCALE REACT APP External libraries
“View” library
Routing
HTTP requests Styling
Form management
LARGE
-
SCALE ANGULAR APP
Frameworks include everything
1 Routing (for SPAs)
2 HTTP requests
3 Remote state management
4 Global state management
5 Styling
6 Form management
7 Animations/transitions
8 UI components
REACT 3RD
-
PARTY LIBRARY ECOSYSTEM
fetch()
Context API Zustand
👉 Library options
for different React
application needs
FRAMEWORKS BUILT ON TOP OF REACT
“Opinionated”
React frameworks
Routing
HTTP requests Styling
Form management
“VANILLA” REACT APP
External libraries
Routing
HTTP requests Styling
Form management
Included out of the box
👉 React frameworks offer many other features: server-side rendering
(
SSR
)
,
static site generation
(
SSG
)
, better developer experience
(
DX
)
, etc.
Full-stack frameworks!
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
HOW REACT WORKS BEHIND THE
SCENES
SECTION SUMMARY
:
PRACTICAL
TAKEAWAYS
🧩 A component is like a blueprint for a piece of UI that will eventually exist on the screen. When we
“use” a component, React creates a component instance, which is like an actual physical
manifestation of a component, containing props, state, and more. A component instance, when
rendered, will return a React element
☎ “Rendering” only means calling component functions and calculating what DOM elements need
to be inserted, deleted, or updated. It has nothing to do with writing to the DOM. Therefore, each
time a component instance is rendered and re-rendered, the function is called again
🔁 Only the initial app render and state updates can cause a render, which happens for the entire
application, not just one single component
👪 When a component instance gets re-rendered, all its children will get re-rendered as well. This
doesn’t mean that all children will get updated in the DOM, thanks to reconciliation, which checks
which elements have actually changed between two renders. But all this re-rendering can still
have an impact on performance (more on that later in the course 👉)
🎯 PRACTICAL SUMMARY
🧬 Diffing is how React decides which DOM elements need to be added or modified. If, between
renders, a certain React element stays at the same position in the element tree, the
corresponding DOM element and component state will stay the same. If the element changed to a
different position, or if it’s a different element type, the DOM element and state will be destroyed
🔑 Giving elements a key prop allows React to distinguish between multiple component instances.
When a key stays the same across renders, the element is kept in the DOM. This is why we need
to use keys in lists. When we change the key between renders, the DOM element will be
destroyed and rebuilt. We use this as a trick to reset state
🪆 Never declare a new component inside another component! Doing so will re-create the nested
component every time the parent component re-renders. React will always see the nested
component as new, and therefore reset its state each time the parent state is updated
🔮 The logic that produces JSX output for a component instance (“render logic”) is not allowed to
produce any side effects: no API calls, no timers, no object or variable mutations, no state
updates. Side effects are allowed in event handlers and useEffect (next section 👉)
🎯 PRACTICAL SUMMARY
📱 The DOM is updated in the commit phase, but not by React, but by a “renderer” called ReactDOM.
That’s why we always need to include both libraries in a React web app project. We can use other
renderers to use React on different platforms, for example to build mobile or native apps
🗂 Multiple state updates inside an event handler function are batched, so they happen all at once,
causing only one re-render. This means we can not access a state variable immediately after
updating it: state updates are asynchronous. Since React 18, batching also happens in timeouts,
promises, and native event handlers.
🌐 When using events in event handlers, we get access to a synthetic event object, not the
browser’s native object, so that events work the same way across all browsers. The difference is
that most synthetic events bubble, including focus, blur, and change, which do not bubble as
native browser events. Only the scroll event does not bubble
🛠 React is a library, not a framework. This means that you can assemble your application using your
favorite third-party libraries. The downside is that you need to find and learn all these additional
libraries. No problem, as you will learn about the most commonly used libraries in this course
🎯 PRACTICAL SUMMARY
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
EFFECTS AND DATA
FETCHING
SECTION
LECTURE
EFFECTS AND DATA FETCHING
THE COMPONENT LIFECYCLE
COMPONENT
(
INSTANCE
)
LIFECYCLE
👉 Component instance is
rendered for the first time
👉 Fresh state and props are
created
💀
🐣 🐓
MOUNT /
INITIAL RENDER
UNMOUNT
👉 Component instance is
destroyed and removed
👉 State and props are
destroyed
HAPPENS WHEN
:
👉 State changes
👉 Props change
👉 Parent re-renders
👉 Context changes
RE
-
RENDER
👋 We can define code to run at
these specific points in time
(
Optional)
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
EFFECTS AND DATA FETCHING
A FIRST LOOK AT EFFECTS
WHERE TO CREATE SIDE EFFECTS
SIDE EFFECT
Triggered by EVENTS
:
onClick, onSubmit, etc.
Triggered by
RENDERING
EVENT
HANDLERS
EFFECTS
(useEffect)
👉 Effects allow us to
write code that will
run at different
moments: mount, re-
render, or unmount
Sometimes this is
not enough for the
application’s needs
(can be made in...)
We need side effects all the
time. They make our
applications do something.
Not in render logic!
👉 REVIEW
:
A side effect is basically any “interaction between a React component and the world outside the component”.
We can also think of a side as “code that actually does something”. Examples: Data fetching, setting up subscriptions,
setting up timers, manually accessing the DOM, etc.
EVENT HANDLERS VS. EFFECTS
EVENT HANDLERS EFFECTS
(
useEffect)
👉 Executed when the corresponding event
happens
👉 Used to react to an event
👉 Executed after the component mounts (initial
render), and after subsequent re-renders
(according to dependency array)
👉 Used to keep a component synchronized
with some external system (in this example,
with the API movie data)
Produce the same result,
but at different moments
(
We’ll come back to all this after using useEffect in practice...)
☝ Preferred way of creating side effects!
Effect
Cleanup
function
Thinking about
synchronization,
not lifecycles
Dependency array
🤔 When?
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
EFFECTS AND DATA FETCHING
THE USEEFFECT DEPENDENCY
ARRAY
WHAT’S THE USEEFFECT DEPENDENCY ARRAY?
👉 By default, effects run after every render. We can
prevent that by passing a dependency array
👉 Without the dependency array, React doesn’t
know when to run the effect
👉 Each time one of the dependencies changes, the
effect will be executed again
☝ Every state variable and prop used inside the
effect MUST be included in the dependency array
THE DEPENDENCY ARRAY
Otherwise, we get a “stale
closure”. We will go more into
depth in a future section 👉
USEEFFECT IS A SYNCHRONIZATION MECHANISM
title
CHANGES
userRating
CHANGES
COMPONENT
STATE/PROPS
EFFECT IS
EXECUTED
AGAIN
EXTERNAL SYSTEM
(
SIDE EFFECT
)
SYNCHRONIZE WITH
DOCUMENT
TITLE
IS UPDATED
DEPENDENCIES 👉 useEffect is like an event listener that is listening for one dependency to
change. Whenever a dependency changes, it will execute the effect again
👉 Effects react to updates to state and props used inside the effect (the
dependencies). So effects are “reactive” (like state updates re-rendering the UI
)
THE MECHANICS
OF EFFECTS
SYNCHRONIZATION AND LIFECYCLE
👉 We can use the dependency array to run effects when the component renders or re-renders
DEPENDENCY
(
STATE OR PROPS
)
CHANGES
EFFECT IS
EXECUTED AGAIN
COMPONENT IS
RE
-
RENDERED
Effects and
component lifecycle
are deeply connected
Effect synchronizes
with x, y, and z
Runs on mount and re-renders
triggered by updating x, y, or z
Effect synchronizes
with no state/props
Runs only on mount
(initial render)
Effect synchronizes
with everything
Runs on every render
(usually bad ⛔)
🔄 SYNCHRONIZATION 🐣 LIFECYCLE
WHEN ARE EFFECTS EXECUTED?
MOUNT
(
INITIAL RENDER
)
COMMIT
BROWSER PAINT
EFFECT ✨
RE
-
RENDER
COMMIT
LAYOUT EFFECT
BROWSER PAINT
UNMOUNT
title = ‘Interstellar’
title = ‘Interstellar Wars’
title CHANGES
EFFECT ✨
time
Another type of effect
that is very rarely necessary
(useLayoutEffect)
If an effect sets state, an
additional render will be required
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
EFFECTS AND DATA FETCHING
THE USEEFFECT CLEANUP
FUNCTION
CLEANUP 🧹
CLEANUP 🧹
WHEN ARE EFFECTS EXECUTED?
MOUNT
(
INITIAL RENDER
)
COMMIT
BROWSER PAINT
EFFECT ✨
RE
-
RENDER
COMMIT
LAYOUT EFFECT
BROWSER PAINT
UNMOUNT
title = ‘Interstellar’
title = ‘Interstellar Wars’
title CHANGES
EFFECT ✨
time
THE CLEANUP FUNCTION
USEEFFECT CLEANUP FUNCTION
👉 Function that we can return from an effect
(optional)
👉 Runs on two different occasions:
Before the effect is executed again
1
2 After a component has unmounted
Execute effect if
dependency array
includes updated data
COMPONENT
RENDERS
Execute
cleanup function
COMPONENT
UNMOUNTS
👉 Necessary whenever the side effect keeps
happening after the component has been
re-rendered or unmounted
☝ Each effect should do only one thing! Use
one useEffect hook for each side effect.
This makes effects easier to clean up
✨ EFFECT 🧹 POTENTIAL
CLEANUP
👉 HTTP request
👉 API subscription
👉 Start timer
👉 Add event listener
Cancel request
Cancel subscription
Stop timer
Remove listener
Examples
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
CUSTOM HOOKS,
REFS, AND MORE
STATE
SECTION
LECTURE
CUSTOM HOOKS, REFS, AND
MORE STATE
REACT HOOKS AND THEIR RULES
REACT HOOKS
WHAT ARE REACT HOOKS?
👉 Special built-in functions that allow us to “hook” into React internals:
👉 Creating and accessing state from Fiber tree
👉 Registering side effects in Fiber tree
👉 Manual DOM selections
👉 Many more…
👉 Always start with “use” (useState, useEffect, etc.)
👉 Enable easy reusing of non-visual logic: we can compose multiple hooks into
our own custom hooks
👉 Give function components the ability to own state and run side effects at
different lifecycle points (before v16.8 only available in class components)
OVERVIEW OF ALL BUILT
-
IN HOOKS
✅ useState
✅ useEffect
👉 useReducer
👉 useContext
🥇 MOST USED
👉 useRef
👉 useCallback
👉 useMemo
👉 useTransition
👉 useDeferredValue
❌ useLayoutEffect
❌ useDebugValue
❌ useImperativeHandle
❌ useId
📜 LESS USED
❌ useSyncExternalStore
❌ useInsertionEffect
🗃 ONLY FOR LIBRARIES
✅ Have learned
👉 Will learn
❌ Will not learn
👋 As of React v18.x
THE RULES OF HOOKS
👋 These rules are automatically enforced by React’s ESLint rules
Only call hooks at the top level
1
2 Only call hooks from React functions
☝ RULES OF
HOOKS
👉 Do NOT call hooks inside conditionals, loops,
nested functions, or after an early return
👉 This is necessary to ensure that hooks are always
called in the same order (hooks rely on this)
👉 Only call hooks inside a function component or a
custom hook
RENDER
☝ Hypothetical example! This
code does NOT work
HOOKS RELY ON CALL ORDER
State A
State B
Effect Z
REACT ELEMENT TREE FIBER TREE
ON INITIAL
RENDER
List built based on
hooks call order
A=7
A=23
7
A===23 is now false, so after re-
render, this hook would no longer
exist, destroying the linked list 😢
false
👉 Hooks need to called in the same order on every render
Props
FIBER
.
.
.
List of hooks
Violates
Rule #1
LINKED LIST OF USED HOOKS
1
State A
1
3
Effect Z
3
2
State B
2
HOOKS RELY ON CALL ORDER
State A
State B
Effect Z
State A
State B
Effect Z
1
3
2
REACT ELEMENT TREE FIBER TREE
Props
List of hooks
FIBER
.
.
.
ON INITIAL
RENDER
LINKED LIST OF USED HOOKS
1
2
3
👍 Correct code!
RENDER
☝ Hooks can only be
called at top level
SAME
ORDER
List built based on
hooks call order
👉 Hooks need to called in the same order on every render
Order num uniquely identifies each hook
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
CUSTOM HOOKS, REFS, AND
MORE STATE
USESTATE SUMMARY
2
UPDATING
STATE
SUMMARY OF DEFINING AND UPDATING STATE
CREATING
STATE
1
👉 Function must be pure and accept no
arguments. Called only on initial render
👉 Function must be pure and return next state
Simple
Based on function
(lazy evaluation)
Simple
Based on current state
Make sure to NOT mutate objects
or arrays, but to replace them
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
CUSTOM HOOKS, REFS, AND
MORE STATE
INTRODUCING ANOTHER HOOK
:
USEREF
REF WITH useRef
WHAT ARE REFS?
👉 “Box” (object) with a mutable .current property that is
persisted across renders (“normal” variables are always reset)
👉 Two big use cases:
Creating a variable that stays the same between
renders (e.g. previous state, setTimeout id, etc.)
1
2 Selecting and storing DOM elements
myRef
.current
(23)
(1000)
We can write to and
read from the ref
using .current
👉 Refs are for data that is NOT rendered: usually only appear in
event handlers or effects, not in JSX (otherwise use state)
☝ Do NOT read write or read .current in render logic (like state)
STATE VS. REFS
❌
STATE
REFS
UPDATING CAUSES
RE
-
RENDER
✅
IMMUTABLE
✅
ASYNCHRONOUS
UPDATES
✅
✅
PERSISTS ACROSS
RENDERS
✅ ❌ ❌
Need to store data Will data change at some point? Regular const variable
NO
Should it re-render component?
YES
State (useState)
YES
Ref (useRef)
NO
(
Taken from lecture “Fundamentals
of state management”)
Examples: preserving
previous state, or storing
the id of a setTimeout
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
CUSTOM HOOKS, REFS, AND
MORE STATE
WHAT ARE CUSTOM HOOKS?
WHEN TO CREATE ONE?
REUSING LOGIC WITH CUSTOM HOOKS
👉 “I need to reuse:”
Does logic contain any hooks?
REGULAR
FUNCTION
NO
CUSTOM
HOOK
YES
COMPONENT
UI LOGIC
👉 Allow us to reuse non-visual logic in multiple components
👉 One custom hook should have one purpose, to make it
reusable and portable (even across multiple projects)
👉 Rules of hooks apply to custom hooks too
Needs to use one
or more hooks
Unlike components,
can receive and
return any relevant
data (usually [] or {})
Function name needs
to start with use
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
REACT BEFORE
HOOKS
:
CLASS
-
BASED REACT
SECTION
LECTURE
REACT BEFORE HOOKS
:
CLASS
-
BASED REACT
CLASS COMPONENTS VS.
FUNCTION COMPONENTS
🏆 Advantages
☎ Event handlers
this.setState()
this.props.X
🎛 Reading props
🚀 Local state
JavaScript function (any type)
💎 How to create
FUNCTION COMPONENTS VS. CLASS COMPONENTS
👍 Easier to build (less boilerplate code)
👍 Cleaner code: useEffect combines all
lifecycle-related code in a single place
👍 Easier to share stateful logic
👍 We don’t need this keyword anymore
👍 Lifecycle might be easier to
understand for beginners
FUNCTION COMPONENTS CLASS COMPONENTS
useState hook
Functions
useEffect hook
Return JSX from function
Destructuring or props.X
ES6 class, extending React.Component
Class methods
Lifecycle methods
Return JSX from render method
v0.13
(
2015
)
v16.8
(
2019, with hooks)
📆 Introduced in
✨ Side effects/lifecycle
💅 Returning JSX
Existed since beginning,
but without hooks
Hooks are THE
big difference
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
PART 03
—
ADVANCED
REACT
+
REDUX
THE ADVANCED
USEREDUCER HOOK
SECTION
LECTURE
THE ADVANCED USEREDUCER
HOOK
MANAGING STATE WITH
USEREDUCER
WHY USEREDUCER?
When components have a lot of state variables and state updates,
spread across many event handlers all over the component
1
2
When multiple state updates need to happen at the same time (as a
reaction to the same event, like “starting a game”)
3
When updating one piece of state depends on one or multiple other
pieces of state
👉 STATE MANAGEMENT WITH useState IS NOT ENOUGH IN CERTAIN SITUATIONS
:
👉 IN ALL THESE SITUATIONS, useReducer CAN BE OF GREAT HELP
MANAGING STATE WITH USEREDUCER
STATE WITH useReducer
👉 An alternative way of setting state, ideal for complex
state and related pieces of state
👉 Stores related pieces of state in a state object
👉 useReducer needs reducer: function containing all logic
to update state. Decouples state logic from component
👉 reducer: pure function (no side effects!
)
that takes
current state and action, and returns the next state
👉 action: object that describes how to update state
👉 dispatch: function to trigger state updates, by
“sending” actions from event handlers to the reducer
Like setState()
with superpowers
Instead of setState()
useState
HOW REDUCERS UPDATE STATE
Object that contains information on
how the reducer should update state
action
type = ‘updateDay’
payload = 23
reducer
NEXT
STATE
CURRENT
STATE
RE
-
RENDER
setState RE
-
RENDER
useReducer
👉 Updating state
in a component
dispatch
RETURNS
NEXT
(
UPDATED
)
STATE
UPDATE
UPDATED STATE
Just like array.reduce(), reducers
accumulate (“reduce”) actions over time
A MENTAL MODEL FOR REDUCERS
👉 REAL
-
WORLD TASK
:
WITHDRAWING $5,000 FROM YOUR BANK ACCOUNT
YOU DO NOT GO TO YOUR BANK AND TAKE MONEY
STRAIGHT FROM THE BANK’S VAULT 😂
A MENTAL MODEL FOR REDUCERS
I would like to withdraw
$5,000 from account 923577
👉 REAL
-
WORLD TASK
:
WITHDRAWING $5,000 FROM YOUR BANK ACCOUNT
STATE
REDUCER
DISPATCHER
ACTION
(
What needs to be updated)
(
Who makes the update)
(
Who requests the update)
(
How to make the update)
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
THE ADVANCED USEREDUCER
HOOK
SECTION SUMMARY
:
USESTATE
VS. USEREDUCER
USESTATE VS. USEREDUCER
useState useReducer
👉 Ideal for single, independent pieces of
state (numbers, strings, single arrays, etc.)
👉 Logic to update state is placed directly in
event handlers or effects, spread all over
one or multiple components
👉 State is updated by calling setState
(setter returned from useState)
👉 Imperative state updates
👉 Easy to understand and to use
👉 Ideal for multiple related pieces of state
and complex state (e.g. object with many
values and nested objects or arrays)
👉 Logic to update state lives in one central
place, decoupled from components: the
reducer
👉 State is updated by dispatching an action
to a reducer
👉 Declarative state updates: complex state
transitions are mapped to actions
👉 More difficult to understand and implement
WHEN TO USE USEREDUCER?
NO
Do states frequently
update together?
Over 3 or 4 pieces of related
state, including objects?
Too many event handlers make
components large and confusing?
Are you willing to implement
slightly more complex code?
useState
useReducer
YES
NO
NO
NO
NO
YES
YES
YES
YES
Just one piece of state?
☝ useState should remain your
default choice for managing state
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
REACT ROUTER
:
BUILDING SINGLE
-
PAGE APPLICATIONS
(
SPA
)
SECTION
LECTURE
REACT ROUTER
:
BUILDING SINGLE
PAGE APPLICATIONS
(
SPA
)
ROUTING AND SINGLE
-
PAGE
APPLICATIONS
(
SPAS
)
WHAT IS ROUTING?
ROUTING
👉 With routing, we match different URLs to different UI views
(
React components): routes
👉 This enables users to navigate between different applications screens, using the browser URL
👉 Keeps the UI in sync with the current browser URL
👉 Allows us to build Single-Page Applications
www.example.com/login
www.example.com/ www.example.com/app
“Client-side routing”
SPA RUNNING ON CLIENT 👩💻
SINGLE
-
PAGE APPLICATION
SINGLE
-
PAGE APPLICATIONS
(
SPA
)
👉 Application that is executed
entirely on the client (browsers)
👉 Routes: different URLs correspond
to different views (components)
👉 JavaScript
(
React) is used to
update the page
(
DOM
)
👉 The page is never reloaded
👉 Feels like a native app
👉 Additional data might be loaded
from a web API
User clicks router link
URL is changed
DOM is updated:
In React, react-
router package
does this job
SERVER
🌐
DOM is updated:
React component
corresponding to the
new URL is rendered
Load data
from web API
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
REACT ROUTER
:
BUILDING SINGLE
PAGE APPLICATIONS
(
SPA
)
STYLING OPTIONS FOR REACT
APPLICATIONS
STYLING OPTIONS IN REACT
👉 CSS Modules
One external file
per component
className prop CSS
Component
👉 CSS-in-JS
Creates new
component
JavaScript
External file or
component file
Component
👉 Utility-first CSS className prop CSS
JSX elements JSX element
👋 Alternative to styling with CSS
:
UI libraries like MUI, Chakra UI, Mantine, etc.
WHERE? HOW? BASED ON
SCOPE
👉 Inline CSS JSX elements style prop CSS
JSX element
👉 CSS or Sass file External file className prop CSS
Entire app
Local
Global, causes problems
STYLING OPTION
React doesn’t care about styling
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
REACT ROUTER
:
BUILDING SINGLE
PAGE APPLICATIONS
(
SPA
)
STORING STATE IN THE URL
THE URL FOR STATE MANAGEMENT
www.example.com/app/cities/lisbon?lat=38.728&lng=-9.141
👉 The URL is an excellent place to store UI state and an alternative to useState in some situations!
Examples: open/closed panels, currently selected list item, list sorting order, applied list filters
1 Easy way to store state in a global place, accessible to all components in the app
Good way to “pass” data from one page into the next page
2
Makes it possible to bookmark and share the page with the exact UI state it had at the time
3
params query string
path
tools:
EXAMPLE
:
PARAMS AND QUERY STRING
www.example.com/app/cities/lisbon?lat=38.728&lng=-9.141
www.example.com/app/cities/berlin?lat=52.536&lng=13.377
👉 City name and GPS location were retrieved
from the URL instead of application state!
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
ADVANCED STATE
MANAGEMENT
:
THE
CONTEXT API
SECTION
LECTURE
ADVANCED STATE MANAGEMENT
:
THE CONTEXT API
WHAT IS THE CONTEXT API?
✅ SOLUTION 2
App
A C
B D E
F
count
✅ SOLUTION 2
:
CONTEXT API
A SOLUTION TO PROP DRILLING
👋 Remember that a good solution to “prop drilling” is better component composition (see “Thinking in React” section)
👉 TASK
:
Passing state into multiple deeply nested child components
⛔ PROBLEM
:
“PROP DRILLING”
App
A C
B D E
F
count
Components
that need
count state
👍 READ STATE FROM EVERYWHERE
💡 SOLUTION 1
:
PASSING PROPS
WHAT IS THE CONTEXT API?
CONTEXT API
👉 System to pass data throughout the app
without manually passing props down the tree
👉 Allows us to “broadcast” global state to the
entire app
Provider: gives all child components
access to value
value: data that we want to make
available (usually state and functions)
Consumers: all components that read the
provided context value
1
2
3
App
A C
B D E
F
value is
updated
All consumers
re-render
(
Consumer)
(
Consumer)
R
E
-
R
E
N
D
E
R
R
E
-
R
E
N
D
E
R
READ VALUE
READ VALUE
Provider
value
A new way of re-rendering
components!
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
ADVANCED STATE MANAGEMENT
:
THE CONTEXT API
THINKING IN REACT
:
ADVANCED
STATE MANAGEMENT
REVIEW
:
WHAT IS STATE MANAGEMENT?
🏠 State management: Giving each piece of state the right home
This lecture!
✅ When to use state
✅ Types of state (accessibility): local vs. global
👉 Types of state (domain): UI vs. remote
👉 Where to place each piece of state
👉 Tools to manage all types of state
From Lecture “Fundamentals of State
Management”. You can keep using this 👌
2⃣
STATE
DOMAIN
TYPES OF STATE
👉 Needed only by one or few
components
👉 Only accessible in component
and child components
👉 Might be needed by many
components
👉 Accessible to every
component in the application
👉 All application data loaded
from a remote server
(
API
)
👉 Usually asynchronous
👉 Needs re-fetching + updating
👉 Everything else 😅
👉 Theme, list filters, form data, etc.
👉 Usually synchronous and stored
in the application
🏠 LOCAL STATE 🌍 GLOBAL STATE
VS.
🌐 REMOTE STATE 🪄 UI STATE
VS.
1⃣
STATE
ACCESSIBILITY
“If this component was
rendered twice, should a
state update in one of them
reflect in the other one?”
NO
STATE PLACEMENT OPTIONS
TOOLS
👇
WHEN TO USE?
👇
🏠 Local component useState, useReducer, or useRef Local state
👪 Parent component useState, useReducer, or useRef Lifting up state
🌐 Context Context API
+
useState or useReducer Global state (preferably UI state)
🗃 3rd-party library Redux, React Query, SWR, Zustand, etc. Global state (remote or UI
)
📍 URL React Router Global state, passing between pages
👩💻 Browser Local storage, session storage, etc. Storing data in user’s browser
🤔 Where to place state?
STATE MANAGEMENT TOOL OPTIONS
1⃣ STATE ACCESSIBILITY
🏠 LOCAL STATE 🌍 GLOBAL STATE
2⃣
STATE
DOMAIN
🌐 REMOTE STATE
🪄 UI STATE
👉 useState
👉 useReducer
👉 useRef
👉 Context API
+
useState/useReducer
👉 Redux, Zustand, Recoil, etc.
👉 React Router
👉 fetch + useEffect +
useState/useReducer
🤔 How to manage different
types of state in practice?
Tools highly
specialized in
handling remote
state
Mostly in small
applications
👉 Context API
+
useState/useReducer
👉 Redux, Zustand, Recoil, etc.
👉 React Query
👉 SWR
👉 RTK Query
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
PERFORMANCE
OPTIMIZATION AND
ADVANCED
USEEFFECT
SECTION
LECTURE
PERFORMANCE OPTIMIZATION
AND ADVANCED USEEFFECT
PERFORMANCE OPTIMIZATION
AND WASTED RENDERS
PERFORMANCE OPTIMIZATION TOOLS
1
PREVENT WASTED
RENDERS
2
IMPROVE APP SPEED/
RESPONSIVENESS
3
REDUCE BUNDLE
SIZE
👉 memo
👉 useMemo
👉 useCallback
👉 Passing elements as
children or regular prop
👉 useMemo
👉 useCallback
👉 useTransition
👉 Using fewer 3rd-party
packages
👉 Code splitting and lazy
loading
👋 This list of tools and techniques is, by no means, exhaustive. You’re already doing
many optimizations by following the best practices I have been showing you ✌
WHEN DOES A COMPONENTS INSTANCE RE
-
RENDER?
👉 A component instance only gets re-rendered in 3 different situations:
🧠
STATE
CHANGES
🌐
CONTEXT
CHANGES
👪
PARENT
RE
-
RENDERS
👉 Wasted render: a render that didn’t produce any change in the DOM
👉 Only a problem when they happen too frequently or when the component is very slow
👋 Remember: a render does not mean that the DOM actually gets updated, it just means
the component function gets called. But this can be an expensive operation.
Creates the false
impression that
changing props
re-renders a
component. This
is NOT true.
Usually no problem, as
React is very fast!
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
PERFORMANCE OPTIMIZATION
AND ADVANCED USEEFFECT
UNDERSTANDING MEMO
WHAT IS MEMOIZATION?
👉 Memoization: Optimization technique that executes a pure function once, and saves the
result in memory. If we try to execute the function again with the same arguments as
before, the previously saved result will be returned, without executing the function again.
function A
Call
function A
Store
result
Cache
Call
function A
New calculated
result
NEW INPUTS
SAME INPUTS
Cached result
👉 Memoize components with memo
👉 Memoize objects with useMemo
👉 Memoize functions with useCallback
1 Prevent wasted renders
2 Improve app speed/responsiveness
memo
THE MEMO FUNCTION
👉 Used to create a component that will not re-
render when its parent re-renders, as long
as the props stay the same between renders
👉 Only affects props! A memoized component
will still re-render when its own state
changes or when a context that it’s
subscribed to changes
👉 Only makes sense when the component is
heavy (slow rendering), re-renders often,
and does so with the same props
Components
re-renders
⛔ REGULAR BEHAVIOR
(
NO MEMO)
Child
re-renders
Components
re-renders
✅ MEMOIZED CHILD WITH MEMO
Memoized child
does NOT
re-render
SAME
PROPS
Memoized child
re-renders
NEW
PROPS
Memoized
component
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
PERFORMANCE OPTIMIZATION
AND ADVANCED USEEFFECT
UNDERSTANDING USEMEMO AND
USECALLBACK
AN ISSUE WITH MEMO
In React, everything is re-created on every render (including
objects and functions)
In JavaScript, two objects or functions that look the same, are
actually different ({} != {})
If props are different between re-renders, memo will not work
If objects or functions are passed as props, the child component
will always see them as new props on each re-render
THEREFORE
We need to memoize objects and functions, to make them stable
(preserve) between re-renders (memoized {} == memoized {})
SOLUTION
TWO NEW HOOKS
:
USEMEMO AND USECALLBACK
useMemo AND useCallback
👉 Used to memoize values (useMemo) and
functions (useCallback) between renders
👉 Values passed into useMemo and useCallback
will be stored in memory (“cached”) and
returned in subsequent re-renders, as long as
dependencies (“inputs”) stay the same
👉 useMemo and useCallback have a
dependency array (like useEffect): whenever
one dependency changes, the value will be
re-created
Components
re-renders
⛔ REGULAR BEHAVIOR
(
NO USEMEMO)
New value
Components
re-renders
✅ MEMOIZING A VALUE WITH USEMEMO
Cached value
is returned.
NO new value
SAME
DEPS
New value
DEPS
CHANGE
Dependencies
TWO NEW HOOKS
:
USEMEMO AND USECALLBACK
useMemo AND useCallback
1
Memoizing props to prevent wasted
renders (together with memo)
2
Memoizing values to avoid expensive
re-calculations on every render
3
Memoizing values that are used in
dependency array of another hook
👉 Used to memoize values (useMemo) and
functions (useCallback) between renders
👉 Values passed into useMemo and useCallback
will be stored in memory (“cached”) and
returned in subsequent re-renders, as long as
dependencies (“inputs”) stay the same
👉 useMemo and useCallback have a
dependency array (like useEffect): whenever
one dependency changes, the value will be
re-created
👉 Only use them for one of the three use cases!
THREE BIG USES CASES
:
For example to
avoid infinite
useEffect loops
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
PERFORMANCE OPTIMIZATION
AND ADVANCED USEEFFECT
OPTIMIZING BUNDLE SIZE WITH
CODE SPLITTING
THE BUNDLE AND CODE SPLITTING
CLIENT
👩💻
SERVER
🌐
ON INITIAL LOAD
SPA RUNS ENTIRELY
ON THE CLIENT
👉 Bundle: JavaScript file containing the entire application code. Downloading the bundle will load the
entire app at once, turning it into a SPA
👉 Bundle size: Amount of JavaScript users have to download to start using the app. One of the most
important things to be optimized, so that the bundle takes less time to download
👉 Code splitting: Splitting bundle into multiple parts that can be downloaded over time (“lazy loading”)
NO MORE FILES
ARE LOADED
Produced by a
tool like Webpack
(inside create-
react-app) or Vite
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
PERFORMANCE OPTIMIZATION
AND ADVANCED USEEFFECT
DON'T OPTIMIZE PREMATURELY!
DON'T OPTIMIZE PREMATURELY!
✅ Find performance bottlenecks using the
Profiler and visual inspection (laggy UI
)
✅ Fix those real performance issues
✅ Memoize expensive re-renders
✅ Memoize expensive calculations
✅ Optimize context if it has many
consumers and changes often
✅ Memoize context value + child components
✅ Implement code splitting + lazy loading
for SPA routes
DON’T!
DO
🚫 Don’t optimize prematurely!
🚫 Don’t optimize anything if there is
nothing to optimize...
🚫 Don’t wrap all components in memo()
🚫 Don’t wrap all values in useMemo()
🚫 Don’t wrap all functions in
useCallback()
🚫 Don’t optimize context if it’s not slow
and doesn’t have many consumers
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
PERFORMANCE OPTIMIZATION
AND ADVANCED USEEFFECT
USEEFFECT RULES AND BEST
PRACTICES
USEEFFECT DEPENDENCY ARRAY RULES
☝ Every state variable, prop, and context value
used inside the effect MUST be included in the
dependency array
☝ All “reactive values” must be included! That
means any function or variable that reference any
other reactive value
☝ Dependencies choose themselves: NEVER ignore
the exhaustive-deps ESLint rule!
☝ Do NOT use objects or arrays as dependencies
(objects are recreated on each render, and React
sees new objects as different, {} !== {})
DEPENDENCY ARRAY RULES
👋 The same rules apply to the dependency arrays
of other hooks: useMemo and useCallback
Reactive value: state, prop, or context value, or
any other value that references a reactive value
All reactive values
used in effect
REMOVING UNNECESSARY DEPENDENCIES
👉 Move function into the effect
👉 If you need the function in multiple places, memoize it (useCallback)
👉 If the function doesn't reference any reactive values, move it out of the component
👉 Instead of including the entire object, include only the properties you need (primitive values)
👉 If that doesn’t work, use the same strategies as for functions (moving or memoizing object)
👉 If you have multiple related reactive values as dependencies, try using a reducer (useReducer)
👉 You don’t need to include setState (from useState) and dispatch (from useReducer) in the
dependencies, as React guarantees them to be stable across renders
🤖 REMOVING FUNCTION DEPENDENCIES
📦 REMOVING OBJECT DEPENDENCIES
🎯 OTHER STRATEGIES
WHEN NOT TO USE AN EFFECT
☝ Effects should be used as a last resort, when no other solution makes
sense. React calls them an “escape hatch” to step outside of React
THREE CASES WHERE EFFECTS ARE OVERUSED
:
1 Responding to a user event. An event handler function should be used instead
2
Fetching data on component mount. This is fine in small apps, but in real-world
app, a library like React Query should be used
3
Synchronizing state changes with one another (setting state based on
another state variable). Try to use derived state and event handlers
We actually do this in the current
project, but for a good reason 😅
Avoid these as a beginner
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
REDUX AND MODERN
REDUX TOOLKIT
(
WITH THUNKS
)
SECTION
LECTURE
REDUX AND MODERN REDUX
TOOLKIT
(
WITH THUNKS
)
INTRODUCTION TO REDUX
WHAT IS REDUX?
REDUX
👉 3rd-party library to manage global state
👉 Standalone library, but easy to integrate with React apps using
react-redux library
👉 All global state is stored in one globally accessible store,
which is easy to update using “actions” (like useReducer)
👉 It’s conceptually similar to using the Context API
+
useReducer
👉 Two “versions”:
(
1
)
Classic Redux,
(
2
)
Modern Redux Toolkit
☝ You need to have a really good understanding of the useReducer hook in order to understand Redux!
Global store is
updated
All consuming
components re-render
We will learn both 😎
DO YOU NEED TO LEARN REDUX?
👋 Historically, Redux was used in most React apps for all global state. Today, that has changed, because there
are many alternatives. Many apps don’t need Redux anymore, unless they need a lot of global UI state.
You might not need to learn Redux…
1 Redux can be hard to learn, and this course teaches it well 😅
2 You will encounter Redux code in your job, so you should understand it
3 Some apps do require Redux (or a similar library)
🤔 WHY LEARN REDUX IN THIS COURSE?
REDUX USE CASES
👋 Historically, Redux was used in most React apps for all global state. Today, that has changed, because there
are many alternatives. Many apps don’t need Redux anymore, unless they need a lot of global UI state.
Ideal use case for
Redux, when there is
lots of state that
updates frequently
For remote global
state, we have better,
more specialized tools
THE REASON WHY MANY
APPS DON’T USE REDUX
THE MECHANISM OF THE USEREDUCER HOOK
Object that contains
information on how the reducer
should update state
CURRENT
STATE
dispatch
NEXT
STATE
reducer
RE
-
RENDER
EVENT HANDLER
IN COMPONENT
action
type = ‘deposit’
payload = 50
THE MECHANISM OF REDUX
STORE
NEXT
STATE
CURRENT
STATE
RE
-
RENDER
reducer
reducer
reducer
...
dispatch
All global state lives in this centralized
container. It’s the single source of truth
of global state in the app
Each reducer is a pure function that calculates the next state (state
transition) based on the action and the current state. Usually one
reducer per app feature (e.g. shopping cart + user data + theme)
action
type = ‘deposit’
payload = 50
EVENT HANDLER
IN COMPONENT
THE MECHANISM OF REDUX
STORE
CURRENT
STATE
dispatch
Action creator
function
reducer
reducer
reducer
...
action
type = ‘deposit’
payload = 50
NEXT
STATE
To automate writing action. Helpful to
keep all possible actions in one central
place.
(
This is a convention, not a must)
RE
-
RENDER
EVENT HANDLER
IN COMPONENT
👉 Redux cycle
👉 Goal: make the state update logic separate from
the rest of the application
THE MECHANISM OF REDUX
STORE
NEXT
STATE
CURRENT
STATE
dispatch
Action creator
function
reducer
reducer
reducer
...
I would like to
deposit $50 from my
account
action
type = ‘deposit’
payload = 50
👉 REAL
-
WORLD TASK
:
DEPOSITING
$50 INTO YOUR BANK ACCOUNT
RE
-
RENDER
EVENT HANDLER
IN COMPONENT
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
REDUX AND MODERN REDUX
TOOLKIT
(
WITH THUNKS
)
REDUX MIDDLEWARE AND
THUNKS
WHAT IS REDUX MIDDLEWARE?
STORE
dispatch MIDDLEWARE
🤔 Where to make an asynchronous API call (or any other async operation) in Redux?
🚫 No asynchronous
operations
🚫 Reducers need to
be pure functions
COMPONENT
🤷 Can make asynchronous
operations and then dispatch
🤷 Fetching data in components
is not ideal
👍 Perfect for asynchronous code
👍 API calls, timers, logging, etc.
👍 The place for side effects
A function that sits between dispatching the action and
the store. Allows us to run code after dispatching, but
before reaching the reducer in the store.
REDUX THUNKS
STORE
dispatch
THUNK
MIDDLEWARE
🚫 No asynchronous
operations
🚫 Reducers need to
be pure functions
COMPONENT
🤷 Can make asynchronous
operations and then dispatch
🤷 Fetching data in components
is not ideal
👍 Perfect for asynchronous code
👍 API calls, timers, logging, etc.
👍 The place for side effects
action
type = ‘deposit’
payload = 50
action
type = ‘deposit’
payload = {data}
🤔 Where to make an asynchronous API call (or any other async operation) in Redux?
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
REDUX AND MODERN REDUX
TOOLKIT
(
WITH THUNKS
)
WHAT IS REDUX TOOLKIT
(
RTK
)
?
WHAT IS REDUX TOOLKIT?
REDUX TOOLKIT
👉 The modern and preferred way of writing Redux code
👉 An opinionated approach, forcing us to use Redux best practices
👉 100% compatible with “classic” Redux, allowing us to use them together
👉 Allows us to write a lot less code to achieve the same result (less “boilerplate”)
👉 Gives us 3 big things (but there are many more…):
We can write code that “mutates” state inside reducers (will be
converted to immutable logic behind the scenes by “Immer” library)
Action creators are automatically created
Automatic setup of thunk middleware and DevTools
1
2
3
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
REDUX AND MODERN REDUX
TOOLKIT
(
WITH THUNKS
)
REDUX VS. CONTEXT API
CONTEXT API VS. REDUX
CONTEXT API
+
useReducer REDUX
👍 Built into React
👍 Easy to set up a single context
👎 Additional state “slide” requires new context
set up from scratch (“provider hell” in App.js)
👎 No mechanism for async operations
👎 Performance optimization is a pain
👎 Only React DevTools
👎 Requires additional package (larger bundle size)
👎 More work to set up initially
👍 Once set up, it’s easy to create additional state
“slices”
👍 Supports middleware for async operations
👍 Performance is optimized out of the box
👍 Excellent DevTools
Keep in mind that we should not use
these solutions for remote state
WHEN TO USE CONTEXT API OR REDUX?
CONTEXT API
+
useReducer REDUX
👉 When you just need to share a value that
doesn’t change often
[
Color theme,
preferred language, authenticated user, …]
👉 When you need to solve a simple prop
drilling problem
👉 When you need to manage state in a local
sub-tree of the app
👉 When you have lots of global UI state that
needs to be updated frequently (because
Redux is optimized for this) [Shopping cart,
current tabs, complex filters or search, …]
👉 When you have complex state with nested
objects and arrays (because you can
mutate state with Redux Toolkit)
“Use the Context API for global state
management in small apps”
“Use Redux for global state
management in large apps”
👋 There is no right answer that fits every project. It all depends on the project needs!
For example in the compound component pattern
These are not
super common
in UI state
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
PART 04
—
PROFESSIONAL
REACT
DEVELOPMENT
REACT ROUTER WITH
DATA LOADING
(
V6.4
+
)
SECTION
LECTURE
REACT ROUTER WITH DATA
LOADING
(
V6.4
+
)
APPLICATION PLANNING
THE PROJECT
:
🍕 FAST REACT PIZZA CO.
REMEMBER OUR VERY FIRST PROJECT?
👉 Now the same restaurant (business)
needs a simple way of allowing
customers to order pizzas and get
them delivered to their home
👉 We were hired to build the application
front-end 🎉
Break the desired UI into components
1
2 Build a static version (no state yet)
3 Think about state management + data flow
🎯 HOW TO PLAN AND BUILD A REACT APPLICATION
FROM THE EARLIER “THINKING IN REACT” LECTURE
:
👉 This works well for small apps with one page and a few features
👉 In real-world apps, we need to adapt this process
1 Gather application requirements and features
3 Divide the application into feature categories
2 Divide the application into pages
👉 Think about the overall and page-level UI
👉 Break the desired UI into components
👉 Design and build a static version (no state yet)
👉 Think about state management + data flow
4 Decide on what libraries to use (technology decisions)
🎯 HOW TO PLAN AND BUILD A REACT APPLICATION
This is just a rough
overview. In the real-world,
things are never this linear
From earlier
From earlier
From earlier
👨💼 PROJECT REQUIREMENTS FROM THE BUSINESS
👉 Very simple application, where users can order one or more pizzas from a menu
👉 Requires no user accounts and no login: users just input their names before using the app
👉 The pizza menu can change, so it should be loaded from an API
👉 Users can add multiple pizzas to a cart before ordering
👉 Ordering requires just the user’s name, phone number, and address
👉 If possible, GPS location should also be provided, to make delivery easier
👉 User’s can mark their order as “priority” for an additional 20% of the cart price
👉 Orders are made by sending a POST request with the order data (user data + selected pizzas) to the API
👉 Payments are made on delivery, so no payment processing is necessary in the app
👉 Each order will get a unique ID that should be displayed, so the user can later look up their order based on the ID
👉 Users should be able to mark their order as “priority” order even after it has been placed
From these requirements, we
can understand the features
we need to implement
STEP 1
✅ DONE
FEATURES
+
PAGES
All features can be placed into
one of these. So this is what the
app will essentially be about
1⃣ User
2⃣ Menu
3⃣ Cart
4⃣ Order
1⃣ Homepage
2⃣ Pizza menu
3⃣ Cart
4⃣ Placing a new order
5⃣ Looking up an order /order/:orderID
/cart
/
/menu
/order/new
FEATURE CATEGORIES NECESSARY PAGES
STEP 2
+
3
STATE MANAGEMENT
+
TECHNOLOGY DECISIONS
1⃣ User
2⃣ Menu
3⃣ Cart
4⃣ Order
STEP 3
+
4
STATE
“DOMAINS” /
“SLICES” TYPES OF
STATE
Global UI state (no accounts, so stays in app)
Global remote state (menu is fetched from API
)
Global UI state (no need for API, just stored in app)
Global remote state (fetched and submitted to API
)
These usually map
quite nicely to the
app features
👉 Routing The standard for React SPAs
Trendy way of styling applications that we want to learn
👉 Styling
New way of fetching data right inside React Router (v6.4
+
)
that is
worth exploring (“render-as-you-fetch” instead of “fetch-on-
render”). Not really state management, as it doesn't persist state.
👉 Remote state
management
State is fairly complex. Redux has many advantages for UI state.
Also, we want to practice Redux a bit more
👉 UI State
management
This is just one of many tech
stacks we could have chosen
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
TAILWIND CSS CRASH
COURSE
:
STYLING
THE APP
SECTION
LECTURE
TAILWIND CSS CRASH COURSE
:
STYLING THE APP
WHAT IS TAILWIND CSS?
WHAT IS TAILWIND CSS?
👉 “A utility-first CSS framework packed with utility classes like flex, text-center and
rotate-90 that can be composed to build any design, directly in your markup
(
HTML or JSX
)
”
👉 Utility-first CSS approach: writing tiny classes with one single purpose, and then combining
them to build entire layouts
👉 In tailwind, these classes are already written for us. So we’re not gonna write any new CSS,
but instead use some of tailwind’s hundreds of classes
TAILWIND CSS
THE BAD
THE GOOD
THE GOOD AND BAD ABOUT TAILWIND
👍 You don’t need to think about class names
👍 No jumping between files to write markup and
styles
👍 Immediately understand styling in any project
that uses tailwind
👍 Tailwind is a design system: many design
decisions have been taken for you, which
makes UIs look better and more consistent
👍 Saves a lot of time, e.g. on responsive design
👍 Docs and VS Code integration are great
👎 Markup
(
HTML or JSX
)
looks very unreadable,
with lots of class names (you get used to it)
👎 You have to learn a lot of class names (but
after a day of usage you know fundamentals)
👎 You need to install and set up tailwind on each
new project
👎 You’re giving up on “vanilla CSS” 😢
👋 Many people love to hate on tailwind
for no reason. Please don’t be that
person! Try it before judging 🙏
These two are enough
to give tailwind a try!
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SETTING UP OUR
BIGGEST PROJECT
+
STYLED
COMPONENTS
SECTION
LECTURE
SETTING UP OUR BIGGEST
PROJECT
+
STYLED COMPONENTS
APPLICATION PLANNING
THE PROJECT
:
THE WILD OASIS
👉 “The Wild Oasis” is a small boutique hotel with 8
luxurious wooden cabins
👉 They need a custom-built application to manage
everything about the hotel: bookings, cabins
and guests
👉 This is the internal application used inside the
hotel to check in guests as they arrive
👉 They have nothing right now, so they also need
the API
👉 Later they will probably want a customer-facing
website as well, where customers will be able to
book stays, using the same API
INTERNAL HOTEL
MANAGEMENT APP
API
CUSTOMER
-
FACING
WEBSITE TO BOOK
STAYS
Later
1 Gather application requirements and features
3 Divide the application into feature categories
2 Divide the application into pages
4 Decide on what libraries to use (technology decisions)
REVIEW
:
HOW TO PLAN A REACT APPLICATION
👨💼 PROJECT REQUIREMENTS FROM THE BUSINESS
👉 Users of the app are hotel employees. They need to be logged into the application to perform tasks
👉 New users can only be signed up inside the applications (to guarantee that only actual hotel employees can get accounts)
👉 Users should be able to upload an avatar, and change their name and password
👉 App needs a table view with all cabins, showing the cabin photo, name, capacity, price, and current discount
👉 Users should be able to update or delete a cabin, and to create new cabins (including uploading a photo)
👉 App needs a table view with all bookings, showing arrival and departure dates, status, and paid amount, as well as cabin and guest data
👉 The booking status can be “unconfirmed” (booked but not yet checked in), “checked in”, or “checked out”. The table should be filterable
by this important status
👉 Other booking data includes: number of guests, number of nights, guest observations, whether they booked breakfast, breakfast price
👉 Users should be able to delete, check in, or check out a booking as the guest arrives (no editing necessary for now)
👉 Bookings may not have been paid yet on guest arrival. Therefore, on check in, users need to accept payment (outside the app), and
then confirm that payment has been received (inside the app)
👉 On check in, the guest should have the ability to add breakfast for the entire stay, if they hadn’t already
👉 Guest data should contain: full name, email, national ID, nationality, and a country flag for easy identification
👉 The initial app screen should be a dashboard, to display important information for the last 7, 30, or 90 days:
👉 A list of guests checking in and out on the current day. Users should be able to perform these tasks from here
👉 Statistics on recent bookings, sales, check ins, and occupancy rate
👉 A chart showing all daily hotel sales, showing both “total” sales and “extras” sales (only breakfast at the moment)
👉 A chart showing statistics on stay durations, as this is an important metric for the hotel
👉 Users should be able to define a few application-wide settings: breakfast price, min and max nights/booking, max guests/booking
👉 App needs a dark mode
STEP 1
👨💼 PROJECT REQUIREMENTS FROM THE BUSINESS
👉 Users of the app are hotel employees. They need to be logged into the application to perform tasks
👉 New users can only be signed up inside the applications (to guarantee that only actual hotel employees can get accounts)
👉 Users should be able to upload an avatar, and change their name and password
👉 App needs a table view with all cabins, showing the cabin photo, name, capacity, price, and current discount
👉 Users should be able to update or delete a cabin, and to create new cabins (including uploading a photo)
👉 App needs a table view with all bookings, showing arrival and departure dates, status, and paid amount, as well as cabin and guest data
👉 The booking status can be “unconfirmed” (booked but not yet checked in), “checked in”, or “checked out”. The table should be filterable
by this important status
👉 Other booking data includes: number of guests, number of nights, guest observations, whether they booked breakfast, breakfast price
👉 Users should be able to delete, check in, or check out a booking as the guest arrives (no editing necessary for now)
👉 Bookings may not have been paid yet on guest arrival. Therefore, on check in, users need to accept payment (outside the app), and
then confirm that payment has been received (inside the app)
👉 On check in, the guest should have the ability to add breakfast for the entire stay, if they hadn’t already
👉 Guest data should contain: full name, email, national ID, nationality, and a country flag for easy identification
👉 The initial app screen should be a dashboard, to display important information for the last 7, 30, or 90 days:
👉 A list of guests checking in and out on the current day. Users should be able to perform these tasks from here
👉 Statistics on recent bookings, sales, check ins, and occupancy rate
👉 A chart showing all daily hotel sales, showing both “total” sales and “extras” sales (only breakfast at the moment)
👉 A chart showing statistics on stay durations, as this is an important metric for the hotel
👉 Users should be able to define a few application-wide settings: breakfast price, min and max nights/booking, max guests/booking
👉 App needs a dark mode
STEP 1
SETTINGS
DASHBOARD
AUTHENTICATION
GUESTS
CHECK IN / OUT
BOOKINGS
CABINS
FEATURES
+
PAGES
STEP 2
+
3
1⃣ Bookings
2⃣ Cabins
3⃣ Guests
4⃣ Dashboard
5⃣ Check in and out
6⃣ App settings
7⃣ Authentication
1⃣ Dashboard
2⃣ Bookings
3⃣ Cabins
4⃣ Booking check in
5⃣ App settings
6⃣ User sign up
7⃣ Login
8⃣ Account settings
/login
/dashboard
/checkin/:bookingID
FEATURE CATEGORIES NECESSARY PAGES
/account
/users
/settings
/cabins
/bookings
👋 We will discuss state later.
Most of it will be global
CSR WITH PLAIN REACT SSR WITH FRAMEWORK
CLIENT
-
SIDE RENDERING
(
CSR
)
OR SERVER
-
SIDE RENDERING
(
SSR
)
?
STEP 4
👉 Used to build Single-Page Applications
(
SPAs)
👉 All HTML is rendered on the client
👉 All JavaScript needs to be downloaded before
apps start running: bad for performance
👉 One perfect use case: apps that are used
“internally” as tools inside companies, that are
entirely hidden behind a login
👉 Used to build Multi-Page Applications
(
MPAs)
👉 Some HTML is rendered in the server
👉 More performant, as less JavaScript needs to
be downloaded
👉 The React team is moving more and more in
this direction
This is exactly what
we want to build in
this project
TECHNOLOGY DECISIONS
👉 Routing The standard for React SPAs
STEP 4
Very popular way of writing component-scoped CSS, right
inside JavaScript. A technology worth learning
👉 Styling
There is almost no UI state needed in this app, so one simple
context with useState will be enough. No need for Redux
👉 UI State
management
Context API
The best way of managing remote state, with features like
caching, automatic re-fetching, pre-fetching, offline support, etc.
Alternatives are SWR and RTK Query, but this is the most popular
👉 Remote state
management
👉 Form
management
Handling bigger forms can be a lot of work, such as manual
state creation and error handling. A library can simplify all this
👉 Other tools React icons / React hot toast / Recharts / date-fns / Supabase
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SUPABASE CRASH
COURSE
:
BUILDING A
BACK
-
END!
SECTION
LECTURE
SUPABASE CRASH COURSE
:
BUILDING A BACK
-
END!
WHAT IS SUPABASE?
WHAT IS SUPABASE?
🌐 BACK
-
END
👉 Service that allows developers to easily create a
back-end with a Postgres database
👉 Automatically creates a database and API so we
can easily request and receive data from the server
👉 No back-end development needed 🥳
👉 Perfect to get up and running quickly!
👉 Not just an API
:
Supabase also comes with easy-
to-use user authentication and file storage
WITH SUPABASE, WE DON’T NEED
TO DO ANY OF THIS MANUALLY!
IT’S ALL INCLUDED
SUPABASE
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
SUPABASE CRASH COURSE
:
BUILDING A BACK
-
END!
MODELING APPLICATION STATE
MODELING STATE
1⃣ Bookings
2⃣ Cabins
3⃣ Guests
4⃣ Dashboard
5⃣ Check in and out
6⃣ App settings
7⃣ Authentication
FEATURE CATEGORIES
STATE “DOMAINS” / “SLICES”
1⃣ Bookings
2⃣ Cabins
3⃣ Guests
4⃣ Settings
5⃣ Users
👉 All this state will be global remote state, stored within Supabase
👉 There will be one table for each state “slice” in the database
THE BOOKINGS TABLE
👉 Bookings are about a guest renting a cabin
👉 So a booking needs information about what guest is booking which cabin: we need to connect them
👉 Supabase uses a Postgres DB, which is SQL (relational DB
)
. So we join tables using foreign keys
BOOKING
GUEST CABIN
id guestId cabinId ...
id id name ...
email ...
We connect a booking with a cabin by
storing the cabin’s id (primary key)
inside the booking cabinId (foreign key)
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
REACT QUERY
:
MANAGING REMOTE
STATE
SECTION
LECTURE
REACT QUERY
:
MANAGING
REMOTE STATE
WHAT IS REACT QUERY?
API
CACHE
WHAT IS REACT QUERY?
API
👉 Powerful library for managing remote (server) state
👉 Many features that allow us to write a lot less code,
while also making the UX a lot better:
👉 Data is stored in a cache
👉 Automatic loading and error states
👉 Automatic re-fetching to keep state synched
👉 Pre-fetching
👉 Easy remote state mutation (updating)
👉 Offline support
👉 Needed because remote state is fundamentally
different from regular
(
UI
)
state
REACT QUERY
“cabins”
fetch(“api.com
/cabins”)
COMPONENT A
fetch(“api.com
/cabins”)
COMPONENT B
“cabins”
“cabins”
NO ADDITIONAL
API REQUEST
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
ADVANCED REACT
PATTERNS
SECTION
LECTURE
ADVANCED REACT PATTERNS
AN OVERVIEW OF REUSABILITY IN
REACT
HOW TO REUSE CODE IN REACT?
Custom hooks
👉 I need to reuse:
Use props as a component
API, to enable custom
behavior. Can be stateless,
stateful, or structural
components
Components
and props
children prop
Render props pattern
Compound component pattern
UI STATEFUL LOGIC
Logic with hooks
For complete control over
what the component
renders, by passing in a
function that tells the
component what to render.
Was more common before
hooks, but still useful
To customize the
component’s content
For very self-contained components that need/want to manage their
own state. Compound components are like fancy super-components
👋 There are even more patterns,
but these ones matter most
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
PART 05
—
FULL
-
STACK
REACT
OVERVIEW OF NEXT.JS
WITH THE "APP"
ROUTER
SECTION
LECTURE
OVERVIEW OF NEXT.JS WITH THE
"APP" ROUTER
AN OVERVIEW OF SERVER
-
SIDE
RENDERING
(
SSR
)
REVIEW
:
THE RISE OF SINGLE
-
PAGE APPLICATIONS
👩💻 CLIENT / FRONT
-
END
🌐 SERVER / BACK
-
END
BROWSER
RENDER
WEBPAGE
SERVER
-
SIDE RENDERING
CLIENT
-
SIDE RENDERING
BROWSER
RENDER
WEBPAGE
API
1 THE “OLD” WAY
2 THE “MODERN” WAY
3 GETTING MODERN AGAIN
CLIENT
-
SIDE RENDERING SERVER
-
SIDE RENDERING
CLIENT
-
SIDE RENDERING
(
CSR
)
VS. SERVER
-
SIDE RENDERING
(
SSR
)
👉 HTML is rendered on the client (the user’s
computer) using JavaScript
👎 Slower initial page loads:
👉 Bigger JavaScript bundle needs to be
downloaded before app starts running
👉 Data is fetched after components mount
👍 Highly interactive: All the code and content
has already been loaded (except data)
👎 SEO can be problematic
👉 HTML is rendered on the server (the
developer’s computer)
👍 Faster initial page loads:
👉 Less JavaScript needs to be downloaded
and executed
👉 Data is fetched before HTML is rendered
👎 Less interactive: Pages might be downloaded
on demand and require full page reloads
👍 SEO-friendly: Content is easier for search
engines to index
CLIENT
-
SIDE RENDERING SERVER
-
SIDE RENDERING
WHEN TO USE CSR AND SSR?
👉 SPAs: Perfect for building highly interactive
web apps
👉 Apps that don’t need SEO
:
👉 Apps that are used “internally” as tools
inside companies
👉 Apps that are entirely hidden behind a login
👉 Content-driven websites or apps where SEO
is essential: E-commerce, blogs, news,
marketing websites, etc.
This is what we’ve
been doing so far
TWO TYPES OF SSR
:
1
Static: HTML generated at build time (often
called Static Site Generation, or SSG
)
2
Dynamic: HTML generated each time server
receives new request (some call only this SSR
)
More on this
later
SSR
TYPICAL TIMELINE OF CSR VS. SSR WITH DATA FETCHING
CSR
SERVER
🌐
CLIENT
👩💻
Fetch data
SERVER
🌐
CLIENT
👩💻
Empty
page
Render app
with data
Fetch data
Render app
with data
Hydrate
First paint
(
FCP
)
Content paint
(
LCP
)
Render
spinner
Content paint
(
LCP
)
First paint
(
FCP
)
Moved to the server
Download
JS bundle
Download
JS bundle
⚡ Much faster!
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
OVERVIEW OF NEXT.JS WITH THE
"APP" ROUTER
THE MISSING PIECE
:
HYDRATION
HYDRATION
WHAT IS HYDRATION?
SERVER
🌐
CLIENT
👩💻
React component tree
SSRd HTML
React app
The React
bundle is
sent as well
Content paint
(
LCP
)
Page interactive
👉 Adds back the interactivity and event
handlers that were lost when HTML was
server-side rendered
👉 Watering the “dry” HTML with the “water”
of interactivity and event handlers
👉 React builds the component tree on the
client and compares it with the actual
SSRd DOM
:
They must be the same so
React can adopt it!
👉 Common hydration error causes:
incorrect HTML element nesting,
different data used for rendering, using
browser-only APIs, side effects, etc.
Rendered
webpage DOM
Hydration
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
OVERVIEW OF NEXT.JS WITH THE
"APP" ROUTER
WHAT IS NEXT.JS?
WHAT IS NEXT.JS?
👉 Meta-framework built on top of React: we still use
components, props, react hooks, etc.
👉 Opinionated way of building React apps: Set of conventions
and best practices regarding routing, data fetching, etc.
👉 Allows us to build complex full-stack web apps and sites
👉 Allows us to use cutting-edge React features that need to
be integrated into a framework: Suspense, Server
Components, Server Actions, steaming, etc.
NEXT.JS
“THE REACT FRAMEWORK FOR THE WEB”
React’s full-stack
architecture vision
THE NEXT.JS KEY INGREDIENTS
SERVER
-
SIDE
RENDERING
(
DYNAMIC
AND STATIC
)
FILE
-
BASED
ROUTING
CONVENTIONS
DATA
FETCHING AND
MUTATION ON
THE SERVER
OPTIMIZATIONS
👉 Dynamic or static
can be selected
for each route
👉 Folders as routes
👉 Special files for
pages, layouts,
loaders, etc.
👉 Fetching data
directly in Server
Components
👉 Mutations in
Server Actions
👉 Images
👉 Fonts
👉 SEO
👉 Preloading
TWO FLAVOURS OF NEXT.JS
:
"APP" AND "PAGES" ROUTER
LEGACY NEXT.JS
:
“PAGES” ROUTER
MODERN NEXT.JS
:
“APP” ROUTER
👉 The first Next.js router since v1
(
2016
)
👉 Still supported and updated in the future
👍 Overall more simple and easy to learn
👎 Simple things like layouts are confusing to
implement
👎 Data fetching using Next.js-specific APIs such
as getStaticProps and getServerSideProps
👉 Introduced in Next.js 13.4
(
2023
)
👉 Recommend for new projects
👉 Implements React’s full-stack architecture: Server
Components, Server Actions, Streaming, etc.
👍 Easy fetching with fetch() right in components
👍 Extremely easy to create layouts, loaders, etc.
👍 More advanced routing (parallel routing, etc.)
👍 Better DX
(
Developer Experience) and UX
👎 Caching is very aggressive and confusing
👎 Steep learning curve (but it’s React)
👋 We’re gonna learn the “app” router from
the start. At the end, there is a section on
the fundamentals of the “pages” router
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
OVERVIEW OF NEXT.JS WITH THE
"APP" ROUTER
WHAT ARE REACT SERVER
COMPONENTS?
WHY REACT SERVER COMPONENTS?
👍 Interactive
👍 Components
👎 Requires lots of JS
👎 Client-server data waterfalls
100%
Server-side
100%
Client-Side
UI = f(state) UI = f(data)
UI = f(data, state)
We “hack” this by storing
fetched data in state too
🤔 What if we could take the best of both worlds?
🧩 The answer is a completely new React paradigm: React Server Components
(
RSC
)
👎 NO components
👍 Easy and fast to fetch all data
👍 Close to the data source
👍 Needs to ship 0 kb of JS
Closer to what a
real-world app is
RSC
WHAT ARE REACT SERVER COMPONENTS?
REACT SERVER COMPONENTS
(
RSC
)
👉 A new full-stack architecture for React apps
👉 Introduces the server as an integral part of
React component trees: server components
👉 We write frontend code next to backend code
in a natural way that “feels” like regular React
☝ RSC is NOT active by default in new React apps
(e.g. Vite apps): it needs to be implemented by
a framework like Next.js (“app router”)
2 SERVER COMPONENTS
1 CLIENT COMPONENTS
👉 “Regular” components
👉 Created with “use client” directive
at the top of the module
👉 Components that are only rendered on
the server
👉 Don’t make it into the bundle
(
0 kb)
👉 We can build the back-end with React!
👉 Default in apps that use the RSC
architecture (like Next.js)
UI = f(state)
UI = f(data)
Name of the
new PARADIGM
Name of the new
COMPONENT TYPE
Client sub-tree. Child modules
need no “use client”
AN EXAMPLE
+
THE SERVER
-
CLIENT BOUNDARY
(
Simplified tree)
CabinRow
App
Menu
Delete
Sidebar
Duplicate
Header Main
“use client”
DarkMode SortBy
Avatar Table
“use client”
“use client”
Also a sub-tree,
but a small one
Server component
Client component
Edit
Split point
between server
and client code
Server-client boundary
SERVER COMPONENTS VS. CLIENT COMPONENTS
🔼 Lifting state up ✅ YES ❌ N.A.
🔽 Props ✅ YES
✅ YES
(
Must be serializable when passed to
client components. No functions or classes)
📥 Data fetching 🤷 Also possible, preferably with library ✅ Preferred. Use async/away in component
📦 Can import
Only client components (can’t go back
in the client-server boundary)
Client and server components
✍ Can render
Client components and server
components passed as props
Client and server components
🔄 When re-render? On state change On URL change (navigation)
CLIENT
COMPONENTS
SERVER
COMPONENTS
⚡ State/hooks ✅ YES ❌ NO
“use client” Default
REACT WITH RSC
A SIMPLE NEW MENTAL MODEL
👩💻 CLIENT
🌐 SERVER
Components
“TRADITIONAL” REACT
View
Server Components
Interaction
UPDATE
STATE
RE
-
RENDER
DISPLAY
FETCH DATA
PROPS
FETCH DATA
UPDATE
URL
RE
-
RENDER
View
Client
Components
DISPLAY
Interaction
UPDATE
STATE
RE
-
RENDER
Navigation
THE GOOD AND BAD OF THE RSC ARCHITECTURE
THE BAD
THE GOOD
👍 We can compose entire full-stack apps with
React components alone (+ server actions 👉)
👍 One single codebase for front and back-end
👍 Server components have more direct and secure
access to the data source (no API, no exposing
API keys, etc.)
👍 Eliminate client-server waterfalls by fetching all
the data needed for a page at once before
sending it to the client (not each component)
👍 “Disappearing code”: server components ship
no JS, so they can import huge libraries “for free”
👎 Makes React more complex
👎 More things to learn and understand
👎 Things like Context API don’t work in server
components
👎 More decisions to make: “Should this be a
client or a server component?”, “Should I fetch
this data on the server or the client?”, etc.
👎 Sometimes you still need to build an API (for
example if you also have a mobile app)
👎 Can only be used within a framework
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
OVERVIEW OF NEXT.JS WITH THE
"APP" ROUTER
HOW RSC WORKS BEHIND THE
SCENES
A QUICK REVIEW OF RENDERING IN REACT
Components
Tree of component instances
(
Component tree)
React element tree (“Virtual DOM”)
RENDER
DOM Elements
(
HTML
)
COMMIT TO DOM
“TRADITIONAL” REACT
B
B
A
C
B A
A B C
B
B
A
C
B D
🤔 How does this work in RSC? 👉
HOW RSC WORKS BEHIND THE SCENES
COMPLETE “VIRTUAL DOM”
C C
C
React
Element
React
Element
React
Element
React
Element
React
Element
React
Element
S
C
S
C
C S
COMPONENT TREE
RENDER
SCs
SERVER CLIENT
“VIRTUAL DOM” OF SC
+
TREES OF CC
(RSC PAYLOAD
)
“HOLE” WHERE THE CC WILL BE RENDERED
Server
component
(
SC
)
render
render
render
The code from the
SC has disappeared
Client
component
(
CC
)
RENDER
CCs
SEND TO
CLIENT
NOT server and client
in the typical sense…
Powered by the framework’s bundler
render
render
render
“use client”
“use client”
C
React
Element
C
C
React
Element
React
Element
React
Element
React
Element
React
Element
🔽 Serialized props passed from SC to CC
📄 URL to script with component code
HOW RSC WORKS BEHIND THE SCENES
S
C C
C S
“use client”
“use client”
COMPLETE “VIRTUAL DOM”
C C
C
React
Element
React
Element
RENDER
SCs
React
Element
React
Element
React
Element
React
Element
React
Element
COMPONENT TREE
SERVER CLIENT
“VIRTUAL DOM” OF SC
+
TREES OF CC
(RSC PAYLOAD
)
“HOLE” WHERE THE CC WILL BE RENDERED
🔽 Serialized props passed from SC to CC
📄 URL to script with component code
The code from the
SC has disappeared
👉 Describes the UI as data, not as finished HTML
👉 When a SC is re-rendered: React is able to merge (“reconcile”) the
current tree on the client with a new tree coming from the server
👉 As a result, UI state can be preserved when a SC re-renders,
instead of completely re-generating the page as HTML
🤔 Why RSC Payload? Why not render SCs as HTML?
RENDER
CCs
SEND TO
CLIENT
NOT server and client
in the typical sense…
Powered by the framework’s bundler
S re-render React
Element
Merge into existing tree
React
Element
A SIMPLIFIED REVIEW
REACT WITH RSC
“TRADITIONAL” REACT
Component tree
“Virtual DOM”
RENDER
DOM Elements
COMMIT
Complete “Virtual DOM”
DOM Elements
Component tree
of SC and CC
“Virtual DOM” of SC
+
Component trees of CC
COMMIT
RENDER SC
RENDER CC
👉 “Hole” where CC will render
👉 Serialized props from SC
👉 URL to script with code
FOR EACH CC IN TREE
:
RSC PAYLOAD
–
SEND “RSC
PAYLOAD”
TO CLIENT
CLIENT
1
2
UI = f(data)(state)
UI = f(data, state)
1 2
☝ Steps don’t wait for one
another. Completed render
work is streamed to client
SERVER
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
OVERVIEW OF NEXT.JS WITH THE
"APP" ROUTER
RSC VS. SSR
:
HOW ARE THEY
RELATED?
REVIEW
:
SERVER
-
SIDE RENDERING
(
SSR
)
SERVER
🌐
CLIENT
👩💻
👉 SSR
:
“Just take this component tree, render it
as HTML, and send that HTML to the browser”
Hydrate
Component tree
Interactive
React App
HTML
RENDER
👉 “Also send the React code to
make the HTML interactive”
👋 We’ll be talking about
dynamic SSR
(
HTML
generated at runtime)
RSC VS. SSR
🤔 What about RSC?
THE RELATIONSHIP BETWEEN RSC AND SSR
Complete “Virtual
DOM”
DOM Elements
Component tree
of SC and CC
“Virtual DOM” of SC
+
Component trees of CC
RENDER SC
RENDER CC
SEND “RSC
PAYLOAD”
CLIENT
SERVER
SERVER
🌐
CLIENT
👩💻
👉 SSR
:
“Just take this component tree, render it
as HTML, and send that HTML to the browser”
Hydrate
Interactive
React App
👉 RSC is NOT the same as SSR
:
they
are separate technologies
👉 RSC does NOT replace SSR
👉 They usually work together:
frameworks can combine them
👉 Both client and server
components are initially rendered
on the server when SSR is used
👉 In the RSC model, “server” just
means “the developer’s computer”
👉 Result: RSC does NOT require a
running web server! Components
could run only once at built time
(static site generation)
Also works like this
when coupled with
RSC. ALL components
are pre-rendered on
the server
Doesn’t need to be
an actual web
server. Simply
“another computer”
HTML
👉 “Also send the React code to
make the HTML interactive”
Doesn’t need
to be a browser
RSC VS. SSR
THE RELATIONSHIP BETWEEN RSC AND SSR
SERVER
🌐
CLIENT
👩💻
👉 SSR
:
“Just take this component tree, render it
as HTML, and send that HTML to the browser”
Hydrate
Interactive
React App
👉 RSC is NOT the same as SSR
:
they
are separate technologies
👉 RSC does NOT replace SSR
👉 They usually work together:
frameworks can combine them
👉 Both client and server
components are initially rendered
on the server when SSR is used
👉 In the RSC model, “server” just
means “the developer’s computer”
👉 Result: RSC does NOT require a
running web server! Components
could run only once at built time
(static site generation)
Component tree
(
SC and CC
)
HTML
RENDER
RSC PAYLOAD
👉 “Also send the React code to
make the HTML interactive”
Hydrate
CCs
Only client
components
So that React has the entire
component tree on the client, not
just HTML. Necessary to preserve
UI state on future SC re-renders
👋 SSR happens only on initial render.
On re-renders, client components
only render on the actual client
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
STARTING TO BUILD
THE "WILD OASIS"
WEBSITE
SECTION
LECTURE
STARTING TO BUILD THE "WILD
OASIS" WEBSITE
PROJECT PLANNING
:
"THE WILD
OASIS" CUSTOMER WEBSITE
THE PROJECT
:
THE WILD OASIS WEBSITE
👉 Remember: “The Wild Oasis” is a small boutique
hotel with 8 luxurious wooden cabins
✅ We built their application to manage everything
about the hotel: bookings, cabins and guests
✅ We also build the API using Supabase
👉 Now they need a customer-facing website
where guests can learn about the hotel, browse
all cabins, reserve a cabin, and create and
update their profile
👉 Updating data in the internal app should update
the website, so we use the same DB and API
👉 We are hired again 😎 🎉
INTERNAL HOTEL
MANAGEMENT APP
API
CUSTOMER
-
FACING
WEBSITE TO BOOK
STAYS
NOW
✅
✅
👨💼 PROJECT REQUIREMENTS FROM THE BUSINESS
PROFILE
ABOUT
AUTHENTICATION
RESERVATIONS
CABINS
👉 Users of the app are potential guests and actual guests
👉 Guests should be able to learn all about the Wild Oasis Hotel
👉 Guests should be able to get information about each cabin and see booked dates
👉 Guests should be able to filter cabins by their maximum guest capacity
👉 Guests should be able to reserve a cabin for a certain date range
👉 Reservations are not paid online. Payments will be made at the property upon arrival. Therefore,
new reservations should be set to “unconfirmed” (booked but not yet checked in)
👉 Guests should be able to view all their past and future reservations
👉 Guests should be able to update or delete a reservation
👉 Guests need to sign up and log in before they can reserve a cabin and perform any operation
👉 On sign up, each guest should get a profile in the DB
👉 Guests should be able to set and update basic data about their profile to make check-in at the
hotel faster
FEATURES
+
PAGES
1⃣ About
2⃣ Cabins
3⃣ Reservations
4⃣ Authentication
5⃣ Profile
1⃣ Homepage
2⃣ About page
3⃣ Cabin overview
4⃣ Cabin detail
5⃣ Login
6⃣ Reservation list
7⃣ Edit reservation
8⃣ Update profile
/account/reservations/edit
/
/cabins/:cabinId
FEATURE CATEGORIES NECESSARY PAGES
/account/profile
/account/reservations
/login
/cabins/
/about
TECHNOLOGY DECISIONS
We might still need global UI state in a Next.js app. For that, we
can use the Context API, Redux, or any of the other solutions. In
this case the Context API will be enough.
👉 UI State
management
Context API
Modern way of writing CSS. Extremely easy to integrate into
Next.js. Most styles and markup will be pre-written anyway in
this project.
👉 Styling
👉 Framework
The most popular React meta-framework. Handles routing, SSR,
data fetching and even remote state management (in a way…),
therefore replacing many tools we had to include before
We’ll use the data and API we already built in the first “Wild Oasis”
project. If you skipped that project, please go back to the
“Supabase” section to set everything up
👉 DB / API
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
DATA FETCHING,
CACHING, AND
RENDERING
SECTION
LECTURE
DATA FETCHING, CACHING, AND
RENDERING
WHAT IS REACT SUSPENSE?
Products Filter
List
WHAT IS REACT SUSPENSE?
SUSPENSE
👉 Built-in React component that we can use to
catch/isolate components (or entire subtrees)
that are not ready to be rendered (“suspending”)
👉 What causes a component to be suspending?
Fetching data (with a supported library)
Loading code (with React’s lazy loading)
👉 Native way to support asynchronous operations
in a declarative way (no more isLoading states
and render logic 🎉)
1
2
Products
App
Nav
Built-in React
component
Component in Next.js
that will fetch data
(will be suspending)
Suspense
HOW DOES SUSPENSE WORK?
App
Nav
☝ Important: Components do NOT automatically suspend just because an async operation is happening inside
them. Integrating async operations with Suspense is hard, so we use libraries
(
React Query, Next.js, etc.)
While rendering, suspending component is found
Go to closest Suspense parent (“boundary”) and
discard already rendered children
Display fallback component/JSX
Render subtree under Suspense boundary
Products Filter
List
Products
Products Filter
List
Products Filter
Suspense
AFTER ASYNC WORK IS DONE
COMPONENT
TREE
These haven’t
been rendered yet
A LOOK BEHIND THE SCENES
Another built-in
component
Fallback
Reconciliation
+
Diffing
FIBER TREE
REPRESENTATION
Triggers Suspense
by throwing promise
throw new Promise(...)
☝ Fallback will NOT be shown again if the Suspense trigger is wrapped in a transition (startTransition). In
Next.js, that’s the case with page navigations. We can reset the Suspense boundary with a unique key prop
Suspense
App
Nav
Activity Spinner
Filter
List
Products
Sibling
Child
🤔 How does Suspense actually know
that a component is suspending?
Activity = ‘Hidden’
Activity = ‘Visible’
Activity = ‘Visible’
State is preserved in
subsequent suspending
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
DATA FETCHING, CACHING, AND
RENDERING
DIFFERENT TYPES OF SSR
:
STATIC
VS. DYNAMIC RENDERING
SERVER
-
SIDE RENDERING IN NEXT.JS
👉 Next.js is a React framework, so rendering is done
by React, following the rules we learned earlier
👉 Remember: Both Server and Client components
are rendered on the server on the initial render
👉 In Next.js, the server-side rendering work is split
by routes
👉 Each route can be either static (also called pre-
rendered) or dynamic
👉 There is also Partial Pre-Rendering
(
PPR
)
which
mixes dynamic and static rendering in the same
route (more later 👉)
/ /search /product
Dynamic
Static Static
Routes of the same app
STATIC VS. DYNAMIC RENDERING
👉 HTML is generated at built time, or
periodically in the background by re-fetching
data
(
ISR, more on this later 👉)
👉 Useful when data doesn’t change often and is
not personalized to user (e.g. product page)
👉 Default rendering strategy in Next.js (even
when a page or component fetches data)
👉 When deployed to Vercel, each static
route is automatically hosted on a CDN
👉 If all routes of an app are static, the entire app
can be exported as a static site
(
SSG
)
STATIC RENDERING DYNAMIC RENDERING
👉 HTML is generated at request time (for each
new request reaches the server)
👉 Makes sense if:
1⃣ The data changes frequently and is
personalized to the user (e.g. cart)
2⃣ Rendering a route requires information that
depends on request (e.g. search params)
👉 A route automatically switches to dynamic
rendering in certain conditions (next slide 👉)
👉 When deployed to Vercel, each dynamic route
becomes a serverless function
Content Delivery
Network
WHEN NEXT.JS SWITCHES TO DYNAMIC RENDERING
👉 Usually, developers don’t directly choose whether a route should be static or dynamic. Next.js
will automatically switch to dynamic rendering in the following scenarios:
👉 We can also force Next.js to render a route dynamically:
👉 export const dynamic = ‘force-dynamic’; from page.js
👉 export const revalidate = 0; from page.js
👉 { cache: 'no-store' } added to a fetch request in any of the route’s server components
👉 noStore() in any of the route’s server components
1 The route has a dynamic segment (page uses params)
/product?quantity=23
2 searchParams are used in the page component
3 headers() or cookies() are used in any of the route’s server components
These influence caching
(
3
)
.
More on this later 👉
4
👉 This is necessary because any of these values can not be known by Next.js at built time
4 An uncached data request is made in any of the route’s server components
SOME TERMINOLOGY YOU MIGHT NEED
👉 Content Delivery Network
(
CDN
)
:
A network of servers located around the globe that cache and deliver a
website’s static content
(
HTML, CSS, JS, images) from as close as possible to each user.
👉 Serverless computing: With the serverless computing model, we can run application code, usually back-
end code, without managing the server ourselves. Instead, we can just run single functions on a cloud
provider: serverless functions. The server is initialized and active only for the duration the serverless
function is running, unlike a traditional Node.js app where the server is constantly running. Remember:
each dynamic route becomes a serverless function.
👉 The “edge”: “As close as possible to the user”. A CDN is part of an “edge” network, but there is also
serverless “edge” computing. This is serverless computing that does not happen on a central server, but
on a network that’s distributed around the globe, as close as possible to the user (like a CDN but for
running code). Important: we can select certain routes to run on the edge when deployed to Vercel.
👉 Incremental Static Regeneration
(
ISR
)
:
A Next.js feature that allows developers to update the content of a
static page, in the background, even after the website has already been built and deployed. This happens
by re-fetching the data of a component or entire route after a certain interval. More on this later 👉
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
DATA FETCHING, CACHING, AND
RENDERING
PARTIAL PRE
-
RENDERING
PARTIAL PRE
-
RENDERING
(
PPR
)
:
A WHOLE NEW WAY OF RENDERING
👉 Idea/problem: Most pages don’t need to be
100% static or 100% dynamic
👉 Solution: Partial Pre-Rendering
👉 New rendering strategy that combines static
and dynamic rendering in the same route
/search /product
100% Dynamic
/
100% Static PPR
80% static
20% dynamic
Static shell
Dynamic content
“Pre-
rendered”
1
2
👉 Result: Even faster pages that can mostly be
delivered from the edge
(
CDN
)
even when
there are small dynamic parts.
A static (pre-rendered) shell is served
immediately from a CDN, leaving holes for
dynamic content
The slower dynamic content is streamed in
as it’s rendered on the server
HOW TO USE PARTIAL PRE
-
RENDERING
👉 PPR needs to be turned on in config file
👉 By default, as much as possible of any route will be statically rendered, creating a static shell
👉 Dynamic parts (components) should be placed inside Suspense boundaries
👉 There are no new APIs to learn 🎉
👉 These boundaries tell Next.js that anything within the boundary is dynamic
👉 The boundary prevents the dynamic part (e.g. reading a header or making a non-cached fetch
request) from spreading onto the entire route.
👉 We provide a static fallback to be shown while the dynamic part is rendering
👉 Dynamic components or sub-trees are inserted into the static shell as they become available
👋 As of Next.js 14, PPR is highly experimental and should not be used in production
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
SECTION
LECTURE
DATA FETCHING, CACHING, AND
RENDERING
HOW NEXT.JS CACHES DATA
NEXT.JS CACHING
CACHING IN NEXT.JS
👉 Caching: Storing fetched or computed data in a temporary location for future access,
instead of having to re-fetch or re-compute the data every time it’s needed
👉 Next.js caches very aggressively: everything that is possible to cache, is cached
👉 Next.js provides APIs for cache revalidation: removing data from the cache and
updating it with fresh data (re-fetched or re-computed)
👍 Makes Next.js apps more performant and saves costs (computing and data access)
👎 Caching always ON by default: strange and unexpected behavior in some situations.
Some caches can’t be turned off 🤯
👎 Very confusing: Many different Next.js APIs affect and control caching
🗺 Where?
⏱ How long?
🧩 Enables
💾 What data?
THE CACHING MECHANISMS
REQUEST
MEMOIZATION
ROUTER
CACHE
DATA CACHE
FULL ROUTE
CACHE
Server Server Server Client
Data fetched with
similar GET requests
(same url and options
in fetch function)
Data fetched in a
route or a single
fetch request
Entire static pages
(
HTML and RSC payload)
Pre-fetched and
visited pages:
static and dynamic
One page
request (one
render, one user)
Indefinitely, even
across de-deploys (can
revalidate or opt out)
Until the “Data cache”
is invalidated (or app
is re-deployed)
30 sec dynamic / 5 min
static (throughout one
user session)
No need to fetch at the top
of tree: the same fetch in
multiple components only
makes one request
Data for static
pages
+
ISR when
revalidated
SPA-like navigation
(instant navigation
and no full reloads)
Static pages
⚡ 👩💻
📄
🗄
👋 This is the behavior in production mode. Caching doesn’t work in development
Only in components (not route
handlers or server actions)
THE CACHING MECHANISMS
🔄 How to revalidate?
🙅 How to opt out?
N.A. 👉 Time-based (automatic) for all data on page:
export const revalidate = <time>; (page.js)
👉 Time-based (automatic) for one data request:
fetch('…', { next: { revalidate: <time>} })
👉 On-demand (manual):
revalidatePath or revalidateTag
👉 revalidatePath or
revalidateTag in SA
👉 router.refresh
👉 cookies.set or
cookies.delete in SA
Not possible
AbortController 👉 Entire page:
export const revalidate = 0; (page.js)
👉 Entire page:
export const dynamic = ‘force-dynamic’; (page.js)
👉 Individual request:
fetch('…', { cache: 'no-store' })
👉 Individual server component: noStore()
REQUEST
MEMOIZATION
ROUTER
CACHE
DATA CACHE
FULL ROUTE
CACHE
These forces page to become
dynamic, which also opts out
of the Full Route Cache
Can be very
problematic
Revalidating Data Cache also
revalidates Full Route Cache
⚡ 👩💻
📄
🗄
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
CLIENT AND SERVER
INTERACTIONS
SECTION
LECTURE
CLIENT AND SERVER
INTERACTIONS
BLURRING THE BOUNDARY
BETWEEN SERVER AND CLIENT
TRADITIONAL
THE SERVER
-
CLIENT BOUNDARY
:
FRONT
-
END VS. BACK
-
END
BACK
-
END
[
API
]
🌐
FRONT
-
END
👩💻
NEXT.JS WITH RSC
+
SA
👉 No clear separation between front-end and back-end anymore
👉 “Knitting”: pieces of server and client code interweave (composability)
👉 Allow us to build true full-stack applications in just one codebase
👉 No need for an intermediary API in many times
👉 Very clear server-client boundary
👉 Communication happens via an API
👉 Once JSON arrives from the back-end,
the front-end takes over
JSON DATA
[
GET
]
MUTATIONS
[
POST, PUT …]
Server
component
Client
component
DATA
:
RENDER DIRECTLY
DATA
:
SEND AS PROPS
MUTATIONS
:
SERVER ACTIONS
(
SA
)
FRONT
-
END
FRONT
-
END
BACK
-
END
BACK
-
END
BACK
-
END
FRONT
-
END
BACK
-
END
E
(
CC
)
C
(
SC
)
A
(
SC
)
B
(
CC
)
D
(
SC
)
E
(
CC
)
C
(
CC
)
DEPENDENCY TREE
(
MODULE IMPORTS
)
IMPORTING VS. RENDERING
📦 Can import Only client components (can’t go back in client-server boundary)
✍ Can render Client components and server components passed as props
CLIENT COMPONENTS SERVER COMPONENTS
👉 Possible if server component is
passed as prop (children or other)
👉 D has already been executed here…
COMPONENT TREE
E
(
CC
)
C
(
CC
)
C
(
SC
)
A
(
SC
)
B
(
CC
)
D
(
SC
)
E
(
CC
)
renders
“use client”
“use client”
imports
🤔 A client component
rendering a server
component?
🤔 Is C a server or
a client
component?
👉 It can be both! A component imported
inside the client-server boundary
creates a client component instance
“use client”
Client-server boundary
Where client-server boundaries are
Client and server components
Client and server components
C
(
SC
)
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
AUTHENTICATION
WITH NEXTAUTH
(
AUTH.JS
)
SECTION
LECTURE
AUTHENTICATION WITH
NEXTAUTH
(
AUTH.JS
)
WHAT IS MIDDLEWARE IN
NEXT.JS?
HOW MIDDLEWARE WORKS IN NEXT.JS
REQUEST RESPONSE
MIDDLEWARE
HOW MIDDLEWARE WORKS IN NEXT.JS
REQUEST
👉 By default, middleware runs before every route in a project,
but we can specify which paths using a matcher
👉 Analogy: chunk of code that’s in every page.js component
👉 Only one middleware function: needs to be exported from
middleware.js (or .ts) in the project root folder
👉 Middleware needs to produce a response: or
RESPONSE
APP ROUTES
MIDDLEWARE
SEND RESPONSE DIRECTLY
(
USUALLY JSON
)
2
👉 Read and set cookies and headers
👉 Authentication and authorization
👉 Server-side analytics
👉 Redirect based on geolocation
👉 A/B testing
1
REDIRECT OR REWRITE TO A ROUTE
2
1
USE CASES
:
MIDDLEWARE DETAILS
:
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
MUTATIONS WITH
SERVER ACTIONS
+
MODERN REACT
HOOKS
SECTION
LECTURE
WHAT ARE SERVER ACTIONS?
MUTATIONS WITH SERVER
ACTIONS
+
MODERN REACT HOOKS
WHAT ARE SERVER ACTIONS?
SERVER
ACTIONS
⚙
SERVER
COMPONENTS
📦
SERVER ACTIONS
👉 The missing piece in the RSC architecture that
enables interactive full-stack applications
👉 Async functions that run exclusively on the
server, allowing us to perform data mutations
RSC ARCHITECTURE
MUTATIONS
2
DATA FETCHING
1
That is able to
handle user input
INTERACTIVE FULL
-
STACK APPLICATIONS
🎯
HOW TO CREATE SERVER ACTIONS
SERVER
🌐
CLIENT
👩💻
“use server” (“API endpoint”)
“use client” (“<script> tag”)
NOT for server components,
but for server actions
1 An async function in a server component.
Can be used in component or passed to a
client component (unlike functions)
SERVER ACTIONS CAN BE DEFINED AT THE TOP OF
:
2 Standalone file: exported functions become
server actions that can be imported into any
component [recommended]
SERVER ACTIONS
👉 The missing piece in the RSC architecture that
enables interactive full-stack applications
👉 Async functions that run exclusively on the
server, allowing us to perform data mutations
👉 Created with the “use server” directive at the
top of the function or an entire module
👉 Behind the scenes: Next.js creates API endpoint
(with URL
)
for each server action. Whenever a
server action is called, a POST request is made to
its URL (the function itself never reaches client)
👉 Unlike server components, server actions actually
require a running web server
We don’t have to manually create APIs
or route handlers to mutate data 🎉
HOW TO USE SERVER ACTIONS
SERVER ACTIONS
👉 The missing piece in the RSC architecture that
enables interactive full-stack applications
👉 Async functions that run exclusively on the
server, allowing us to perform data mutations
👉 Created with the “use server” directive at the
top of the function or an entire module
1 action attribute in a <form> element (in
server and client components)
SERVER ACTIONS CAN BE CALLED FROM
:
2 Event handlers (only client components)
3 useEffect (only client components)
IN SERVER ACTIONS, WE CAN
:
👉 Perform data mutations (create, update, delete)
👉 Update the UI with new data: Revalidate cache
with revalidatePath and revalidateTag
👉 Work with cookies
👉 Many more…
👉 Behind the scenes: Next.js creates API endpoint
(with URL
)
for each server action. Whenever a
server action is called, a POST request is made to
its URL (the function itself never reaches client)
👉 Unlike server components, server actions actually
require a running web server
Code is running on the back-end, so
we need to assume inputs are unsafe

More Related Content

PPTX
Presentation on "An Introduction to ReactJS"
Flipkart
 
PPTX
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
PDF
FRONTEND DEVELOPMENT WITH REACT.JS
IRJET Journal
 
PPTX
React_Complete.pptx
kamalakantas
 
PPTX
ReactJS
Ram Murat Sharma
 
PDF
Tech Talk on ReactJS
Atlogys Technical Consulting
 
PPSX
React introduction
Kashyap Parmar
 
PDF
The Road To Redux
Jeffrey Sanchez
 
Presentation on "An Introduction to ReactJS"
Flipkart
 
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
FRONTEND DEVELOPMENT WITH REACT.JS
IRJET Journal
 
React_Complete.pptx
kamalakantas
 
Tech Talk on ReactJS
Atlogys Technical Consulting
 
React introduction
Kashyap Parmar
 
The Road To Redux
Jeffrey Sanchez
 

Similar to theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri (20)

PPTX
React for JavaScipt Introduction and functions
MaithiliGogteParanja
 
PPTX
unit 2 React js.pptxdgdgdgdgdgdgdgdgdsgdgdg
zmulani8
 
PPTX
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
PDF
React & Flux Workshop
Christian Lilley
 
PPTX
react js training|react js training in mumbai|React js classes in mumbai
EsgbnmkPhcm
 
PPTX
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
PPTX
React js
Nikhil Karkra
 
PPTX
React Workshop: Core concepts of react
Imran Sayed
 
PDF
Welcome to React & Flux !
Ritesh Kumar
 
PDF
React Fundamentals - Jakarta JS, Apr 2016
Simon Sturmer
 
PPTX
ReactJs
Sahana Banerjee
 
PDF
React js
Rajesh Kolla
 
PPTX
React + Flux = Joy
John Need
 
PPTX
reactJS
Syam Santhosh
 
PDF
An Intense Overview of the React Ecosystem
Rami Sayar
 
PPTX
React workshop
Imran Sayed
 
PDF
React in Action ( PDFDrive ).pdf
almako2
 
PPTX
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
PDF
An Overview of the React Ecosystem
FITC
 
PPTX
Getting started with react &amp; redux
Girish Talekar
 
React for JavaScipt Introduction and functions
MaithiliGogteParanja
 
unit 2 React js.pptxdgdgdgdgdgdgdgdgdsgdgdg
zmulani8
 
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
React & Flux Workshop
Christian Lilley
 
react js training|react js training in mumbai|React js classes in mumbai
EsgbnmkPhcm
 
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
React js
Nikhil Karkra
 
React Workshop: Core concepts of react
Imran Sayed
 
Welcome to React & Flux !
Ritesh Kumar
 
React Fundamentals - Jakarta JS, Apr 2016
Simon Sturmer
 
React js
Rajesh Kolla
 
React + Flux = Joy
John Need
 
reactJS
Syam Santhosh
 
An Intense Overview of the React Ecosystem
Rami Sayar
 
React workshop
Imran Sayed
 
React in Action ( PDFDrive ).pdf
almako2
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
An Overview of the React Ecosystem
FITC
 
Getting started with react &amp; redux
Girish Talekar
 
Ad

Recently uploaded (20)

PDF
4286820232025-07-21-611256.pdf Supreme Court
sabranghindi
 
PDF
Forestry Commission boss sues Dakyehene of New 88.3 FM, demands GH¢20 million...
Kweku Zurek
 
PPTX
OEC.pptxdddfffffffgsjjssuxjdjdussskddiixd
athulpopzz706
 
PPTX
71 Strategies to Control Legal Expenses.pptx
jamesstapleton21
 
PPTX
The Election Process in India , election system
luckybhagyasri13
 
PDF
STATUTE-130-Pg2000.pdf LEI MAGNITISKY U.S.A.
xyzabcd012345098765
 
PDF
AHRP LB - The Regulatory Framework and Practice of Absentee Land in Indonesia...
AHRP Law Firm
 
PPTX
5 Crucial Facts About California’s Three Strikes Law & Its Real Impact.pptx
charlottejim674
 
PPTX
Rule of Strict Interpretation.pptx AND G
DhrumilRanpura1
 
PPTX
LLM Presentation_Manas Dash in masterin law.pptx
Lupin32
 
PPTX
First Responder course seminar for Philippine National Police.pptx
QPPOOperation
 
PPT
EGMGPLVAW powerpoint (Rowena Guanzon).ppt
delomisoljd
 
PDF
Top 10 Legal Consultants Shaping Business Strategy in 2025
timeiconic007
 
PPTX
Case Law Presentations- Group Project-Brady vs Maryland.pptx
snyderjohn9247
 
PPTX
Military Unit symbols, vision and conclusion
antarikshdhaka
 
PDF
Anticipatory bail order delay 698 days Advocate Rohit Dandriyal.pdf
chamberofadvrohitdan
 
PPTX
Compensation acts(Maternity, Workmen's compensation, Gratuity, ESI).pptx
Sunaina44
 
PPTX
Grant Of Patent application process.pptx
blossomjasmine085
 
PPTX
TRADE UNION ACT 1926(Indian labor law).pptx
Sunaina44
 
PDF
Female Giggers' Discrimination - Dr. Yanki Hartijasti.pdf
sakshikothari33
 
4286820232025-07-21-611256.pdf Supreme Court
sabranghindi
 
Forestry Commission boss sues Dakyehene of New 88.3 FM, demands GH¢20 million...
Kweku Zurek
 
OEC.pptxdddfffffffgsjjssuxjdjdussskddiixd
athulpopzz706
 
71 Strategies to Control Legal Expenses.pptx
jamesstapleton21
 
The Election Process in India , election system
luckybhagyasri13
 
STATUTE-130-Pg2000.pdf LEI MAGNITISKY U.S.A.
xyzabcd012345098765
 
AHRP LB - The Regulatory Framework and Practice of Absentee Land in Indonesia...
AHRP Law Firm
 
5 Crucial Facts About California’s Three Strikes Law & Its Real Impact.pptx
charlottejim674
 
Rule of Strict Interpretation.pptx AND G
DhrumilRanpura1
 
LLM Presentation_Manas Dash in masterin law.pptx
Lupin32
 
First Responder course seminar for Philippine National Police.pptx
QPPOOperation
 
EGMGPLVAW powerpoint (Rowena Guanzon).ppt
delomisoljd
 
Top 10 Legal Consultants Shaping Business Strategy in 2025
timeiconic007
 
Case Law Presentations- Group Project-Brady vs Maryland.pptx
snyderjohn9247
 
Military Unit symbols, vision and conclusion
antarikshdhaka
 
Anticipatory bail order delay 698 days Advocate Rohit Dandriyal.pdf
chamberofadvrohitdan
 
Compensation acts(Maternity, Workmen's compensation, Gratuity, ESI).pptx
Sunaina44
 
Grant Of Patent application process.pptx
blossomjasmine085
 
TRADE UNION ACT 1926(Indian labor law).pptx
Sunaina44
 
Female Giggers' Discrimination - Dr. Yanki Hartijasti.pdf
sakshikothari33
 
Ad

theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri

  • 1. SLIDES FOR THEORY LECTURES ( DON’T SKIP THEM, THEY ARE SUPER IMPORTANT 🤓) Subscribe here Follow me here
  • 2. 📖 TABLE OF CONTENTS : THEORY LECTURES ( CLICK THE TITLES ) Watch Before You Start! Why Do front-end Frameworks exist? What is React? Setting Up a New React Project: The Two Options Components as Building Blocks What is JSX? Separation of Concerns Props, Immutability, and One-Way Data Flow The Rules of JSX Section Summary What is State in React? The Mechanics of State More Thoughts About State + State Guidelines State vs. Props What is "Thinking in React"? Fundamentals of State Management Derived State The children Prop: Making a Reusable Button How to Split a UI Into Components Component Categories Component Composition Props as a Component API Components, Instances, and Elements How Rendering Works: Overview How Rendering Works: The Render Phase How Rendering Works: The Commit Phase How Diffing Works The Key Prop Rules for Render Logic: Pure components State Update Batching How Events Work in React Libraries vs. Frameworks & The React Ecosystem Section Summary: Practical Takeaways The Component Lifecycle A First Look at Effects The useEffect Dependency Array The useEffect Cleanup Function React Hooks and Their Rules useState Summary 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 33 34 35 36 37 38 39
  • 3. 📖 TABLE OF CONTENTS : THEORY LECTURES ( CLICK THE TITLES ) Managing State With useReducer Section Summary: useState vs. useReducer Routing and Single-Page Applications ( SPAs) Styling Options For React Applications What is the Context API? Thinking In React: Advanced State Management Performance Optimization and Wasted Renders Understanding memo Understanding useMemo and useCallback Optimizing Bundle Size With Code Splitting Don't Optimize Prematurely! useEffect Rules and Best Practices Introduction to Redux Redux Middleware and thunks What is Redux Toolkit ( RTK ) ? Redux vs. Context API Application Planning (“Fast React Pizza Co.”) What is Tailwind CSS? Application Planning (“The Wild Oasis”) What is Supabase? Modeling Application State What is React Query? An Overview of Reusability in React Introducing Another Hook: useRef What are Custom Hooks? When to Create One? Class Components vs. Function Components 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 An Overview of Server-Side Rendering ( SSR ) The Missing Piece: Hydration What is Next.js? What are React Server Components? ( RSC Part 1 ) How RSC Works Behind the Scenes ( RSC Part 2 ) RSC vs. SSR : How are They Related? ( RSC Part 3 ) Project Planning: "The Wild Oasis" Website What is React Suspense? Types of SSR : Static vs. Dynamic Rendering Partial Pre-Rendering How Next.js Caches Data Blurring the Boundary Between Server and Client What is Middleware in Next.js? 66 67 68 69 70 71 72 73 74 75 76 77 78 What are Server Actions? 79
  • 7. ✌ This course is for everyone! So please don’t write a bad review right away if the course is too easy, or too hard, or progressing too slow, or too fast for you ✌ To make the course perfect for YOU : rewatch lectures, jump to other sections, watch the course with slower or faster speed, or ask questions Please don’t be that person. Everyone is different... Unless the course is truly terrible (it’s not 😛) SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
  • 8. SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀 😱 You don’t need to watch the entire course in order to learn React! If you are in a hurry, can cut the course length in HALF by skipping optional sections and practice parts
  • 9. 👩💻 You need to code along with me! You will learn ZERO React skills by just sitting and watching me code. You really have to write code YOURSELF! SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
  • 10. 😅 In the first sections of the course, don’t worry about WHY and HOW things work, or about React “best practices”. While learning, we just want to make things WORK. We will worry about everything else later in the course SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
  • 11. ⁉ If you have a problem or a question, start by trying to solve it yourself! This is essential for your progress. If you can’t solve it, check the Q&A section. If that doesn’t help, you can ask a new question. Use a short description, and post code on codesandbox.io 1 2 3 SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
  • 12. ⏳ Before moving on from a section, make sure that you understand exactly what was covered. Take a break, review the code we wrote, review your notes, review the projects we built, and maybe even write some code yourself ✅ SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀 ✅ ✅
  • 13. 🖥 I recorded this course on a Mac, but everything works the exact same way on Windows or Linux. If something doesn’t work on your computer, it’s NOT because you’re using a different OS SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
  • 14. 😍 Most importantly, have fun! It’s so rewarding to see an app come to life that YOU have built YOURSELF! So if you’re feeling frustrated, stop whatever you’re doing, and come back later! And I mean REAL fun 😅 SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
  • 17. A FIRST LOOK AT REACT
  • 19. SECTION LECTURE A FIRST LOOK AT REACT WHY DO FRONT - END FRAMEWORKS EXIST?
  • 20. THE RISE OF SINGLE - PAGE APPLICATIONS 👩💻 CLIENT / FRONT - END 🌐 SERVER / BACK - END BROWSER DATA VIEW RENDER WEBPAGE SERVER - SIDE RENDERING CLIENT - SIDE RENDERING The “old” way (but now getting modern again…) The “modern” way BROWSER VIEW RENDER WEBPAGE API DATA 👉 Single-Page Application ( SPA ) 👉 Developers started writing more and more JS code, which led to…
  • 21. SINGLE - PAGE APPLICATIONS WITH VANILLA JAVASCRIPT? Handling data + displaying data in a user interface 👉 Front-end web applications are all about… User interface needs to stay in sync with data Very hard problem to solve! DATA UI
  • 22. KEEPING UI IN SYNC WITH DATA ☝ Keeping UI and data in sync would be virtually impossible with just vanilla JavaScript DATA DATA DATA DATA ?? Piece of data = Piece of state
  • 23. PROBLEMS WITH SINGLE - PAGE APPLICATIONS WITH VANILLA JAVASCRIPT? Handling data + displaying data in a user interface 👉 Front-end web applications are all about… User interface needs to stay in sync with data Very hard problem to solve! 1 Requires lots of direct DOM manipulation and traversing (imperative) 👉 “Spaghetti code” 🍝 2 Data (state) is usually stored in the DOM, shared across entire app 👉 Hard to reason + bugs 🐛 DATA UI
  • 24. 1 JavaScript front-end frameworks exist because… KEEPING A USER INTERFACE IN SYNC WITH DATA IS REALLY HARD AND A LOT OF WORK Front-end frameworks solve this problem and take hard work away from developers 🎉 WHY DO FRONT - END FRAMEWORKS EXIST? 2 They enforce a “correct” way of structuring and writing code (therefore contributing to solving the problem of “spaghetti code” 🍝) 3 They give developers and teams a consistent way of building front-end applications DATA UI Different approaches, same goal
  • 26. SECTION LECTURE A FIRST LOOK AT REACT WHAT IS REACT?
  • 27. WHAT IS REACT? REACT JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES
  • 28. WHAT IS REACT? REACT EXTREMELY POPULAR, DECLARATIVE, COMPONENT - BASED, STATE - DRIVEN JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES, CREATED BY FACEBOOK 🤔 🤯 🤣
  • 29. 👉 Components are the building blocks of user interfaces in React REACT IS BASED ON COMPONENTS 👉 We build complex UIs by building and combining multiple components Webpage Component 1 Component 2 Component 3 Based on components Extremely popular JavaScript library State-driven Declarative Created by facebook
  • 30. REACT IS BASED ON COMPONENTS NavBar Search Map Results Listing Listing Listing Based on components Extremely popular JavaScript library State-driven Created by facebook Declarative
  • 31. REACT IS DECLARATIVE 👉 We describe how components look like and how they work using a declarative syntax called JSX 👉 Declarative: telling React what a component should look like, based on current data/state 👉 React is abstraction away from DOM : we never touch the DOM 👉 JSX : a syntax that combines HTML, CSS, JavaScript, as well as referencing other components JSX returned from a component Based on components Declarative Extremely popular JavaScript library State-driven Created by facebook
  • 32. REACT IS STATE - DRIVEN UI 1 RENDER 3 UPDATE STATE 4 RE - RENDER Components written with JSX Search apartments 2 REACT REACTS TO STATE CHANGES BY RE - RENDERING THE UI STATE Example: array of apartments Based on components State-driven Declarative Extremely popular JavaScript library Created by facebook
  • 33. REACT IS A JAVASCRIPT LIBRARY 🤔 Is React a library or a framework? JavaScript library Based on components State-driven Declarative Extremely popular Created by facebook Because React is only the “view” layer. We need to pick multiple external libraries to build a complete application Complete frameworks built on top of React
  • 34. REACT IS EXTREMELY POPULAR ( Weekly downloads from NPM ) ✅ Many large companies have adopted React ✅ Huge job market with high demand for React developers 🤑 ✅ Large and vibrant React developer community ✅ Gigantic third-party library ecosystem React is extremely popular Extremely popular JavaScript library Based on components State-driven Declarative Created by facebook
  • 35. REACT WAS CREATED BY FACEBOOK Extremely popular JavaScript library Based on components State-driven Declarative Created by facebook 👉 React was created in 2011 by Jordan Walke, an engineer working at Facebook at the time 👉 React was open-sourced in 2013, and has since then completely transformed front-end web development
  • 36. 🎯 SUMMARY 1 Rendering components on a webpage ( UI ) based on their current state 2 Keeping the UI in sync with state, by re-rendering (reacting) when state changes Component 3 Component 1 Component 2 RENDER RE - RENDER
  • 38. SECTION LECTURE A FIRST LOOK AT REACT SETTING UP A NEW REACT PROJECT : THE TWO OPTIONS
  • 39. THE TWO OPTIONS FOR SETTING UP A RECT PROJECT 👉 Complete “starter kit” for React applications 👍 Everything is already configured: ESLint, Prettier, Jest, etc. 👎 Uses slow and outdated technologies (i.e. webpack) 👉 Modern build tool that contains a template for setting up React applications 👎 Need to manually set up ESLint (and others) 👍 Extremely fast hot module replacement ( HMR ) and bundling VITE CREATE - REACT - APP ✅ Use for tutorials or experiments ⛔ Don’t use for a real-world app ✅ Use for modern real-world apps By the end of the course Most of the course Jest
  • 40. WHAT ABOUT REACT FRAMEWORKS? 👉 The React team now advises to use a “React Framework” for new projects 👉 Many people think that this is not the best idea: “vanilla” React apps are important too! 👉 This only makes sense for building actual products, not for learning React 👉 Of course, you still need to learn React itself ✌ Don’t worry about this recommendation for now. Let’s just learn React! 👉 react.dev
  • 43. SECTION LECTURE WORKING WITH COMPONENTS, PROPS, AND JSX COMPONENTS AS BUILDING BLOCKS
  • 44. COMPONENTS AS BUILDING BLOCKS COMPONENTS 👉 React applications are entirely made out of components 👉 Building blocks of user interfaces in React
  • 45. COMPONENTS AS BUILDING BLOCKS COMPONENTS Webpage ( UI ) Component A Component B Component B Component C Component A Data Appearance Logic 👉 React applications are entirely made out of components 👉 Building blocks of user interfaces in React 👉 Piece of UI that has its own data, logic, and appearance (how it works and looks) 👉 We build complex UIs by building multiple components and combining them
  • 46. COMPONENTS AS BUILDING BLOCKS COMPONENTS 👉 React applications are entirely made out of components 👉 Building blocks of user interfaces in React 👉 Piece of UI that has its own data, logic, and appearance (how it works and looks) 👉 We build complex UIs by building multiple components and combining them 👉 Components can be reused, nested inside each other, and pass data between them VideoPlayer QuestionList Question Question Question RefineQuestions Filters Menu
  • 50. Component Data Appearance Logic WHAT IS JSX? JSX 👉 Declarative syntax to describe what components look like and how they work 👉 Components must return a block of JSX 👉 Extension of JavaScript that allows us to embed JavaScript, CSS, and React components into HTML Appearance JSX returned from component
  • 51. WHAT IS JSX? JSX 👉 Declarative syntax to describe what components look like and how they work 👉 Components must return a block of JSX 👉 Extension of JavaScript that allows us to embed JavaScript, CSS, and React components into HTML 👉 Each JSX element is converted to a React.createElement function call 👉 We could use React without JSX
  • 52. JSX IS DECLARATIVE IMPERATIVE DECLARATIVE 👉 Manual DOM element selections and DOM traversing 👉 Step-by-step DOM mutations until we reach the desired UI 👉 Describe what UI should look like using JSX, based on current data 👉 React is an abstraction away from DOM : we never touch the DOM 👉 Instead, we think of the UI as a reflection of the current data “How to do things” “What we want”
  • 54. SECTION LECTURE WORKING WITH COMPONENTS, PROPS, AND JSX SEPARATION OF CONCERNS
  • 55. SEPARATION OF CONCERNS? ONE TECHNOLOGY PER FILE Rise of interactive SPAs Logic and UI are tightly coupled JavaScript is in charge of HTML Why keep them separated? React Components + JSX “Traditional” separation of concerns
  • 56. SEPARATION OF CONCERNS? ONE COMPONENT PER FILE Rise of interactive SPAs Logic and UI are tightly coupled JavaScript is in charge of HTML Why keep them separated? React Components + JSX HTML and JS are colocated Component Data Appearance Logic Fundamental reason for components
  • 57. SEPARATION OF CONCERNS! ONE TECHNOLOGY PER FILE Rise of interactive SPAs Logic and UI are tightly coupled JavaScript is in charge of HTML Why keep them separated? React Components + JSX ONE COMPONENT PER FILE Question Menu Filters Player “Traditional” separation of concerns COMPLETELY NEW PARADIGM Each component is concerned with one piece of the UI
  • 59. SECTION LECTURE WORKING WITH COMPONENTS, PROPS, AND JSX PROPS, IMMUTABILITY, AND ONE - WAY DATA FLOW
  • 60. Header Menu Footer App Pizza Order Pizza Pizza REVIEWING PROPS PROPS 👉 Props are used to pass data from parent components to child components (down the component tree)
  • 61. REVIEWING PROPS PROPS 👉 Props are used to pass data from parent components to child components (down the component tree) 👉 Essential tool to configure and customize components (like function parameters) 👉 With props, parent components control how child components look and work
  • 62. REVIEWING PROPS PROPS 👉 Props are used to pass data from parent components to child components (down the component tree) 👉 Essential tool to configure and customize components (like function parameters) 👉 With props, parent components control how child components look and work 👉 Anything can be passed as props: single values, arrays, objects, functions, even other components
  • 63. PROPS ARE READ - ONLY! Data Appearance Logic Component Props State Data Appearance Logic State is internal data that can be updated by the component’s logic Parent Component Props is data coming from the outside, and can only be updated by the parent component ☝ Props are read-only, they are immutable! This is one of React’s strict rules. ☝ If you need to mutate props, you actually need state 👉 Mutating props would affect parent, creating side effects (not pure) 👉 Components have to be pure functions in terms of props and state 👉 This allows React to optimize apps, avoid bugs, make apps predictable WHY? Don’t do this!
  • 64. ONE - WAY DATA FLOW App Pizza Pizza Pizza Order Header Menu Footer ONE - WAY DATA FLOW... 👍 ... makes applications more predictable and easier to understand 👍 … makes applications easier to debug, as we have more control over the data 👍 … is more performant Angular has two-way data flow
  • 67. DIFFERENCES BETWEEN JSX AND HTML RULES OF JSX 👉 className instead of HTML’s class 👉 htmlFor instead of HTML’s for 👉 Every tag needs to be closed. Examples: <img /> or <br /> 👉 All event handlers and other properties need to be camelCased. Examples: onClick or onMouseOver 👉 Exception: aria-* and data-* are written with dashes like in HTML 👉 CSS inline styles are written like this: {{<style>}} (to reference a variable, and then an object) 👉 CSS property names are also camelCased 👉 Comments need to be in {} (because they are JS ) GENERAL JSX RULES 👉 JSX works essentially like HTML, but we can enter “JavaScript mode” by using {} (for text or attributes) 👉 We can place JavaScript expressions inside {}. Examples: reference variables, create arrays or objects, [].map(), ternary operator 👉 Statements are not allowed (if/else, for, switch) 👉 JSX produces a JavaScript expression 1⃣ We can place other pieces of JSX inside {} 2⃣ We can write JSX anywhere inside a component (in if/else, assign to variables, pass it into functions) == 👉 A piece of JSX can only have one root element. If you need more, use <React.Fragment> (or the short <>)
  • 70. App Pizza Pizza Pizza Order Header Menu Footer 🎯 SECTION SUMMARY Component Data Appearance: JSX JS Logic To pass data from parent to child components Props List of Pizzas Rendering multiple components at once using the JavaScript .map() method Components in component tree “HTML” CSS JS inside {} JSX block is what we return from a component Components can be conditionally rendered using JS tools: &&, ?, and multiple return
  • 73. SECTION LECTURE STATE, EVENTS, AND FORMS : INTERACTIVE COMPONENTS WHAT IS STATE IN REACT?
  • 74. Rest of the course... What is state and why do we need it? 1 2 How to use state in practice? 👉 useState 👉 useReducer 👉 Context API 3 Thinking about state 👉 When to use state 👉 Where to place state 👉 Types of state 📚 WHAT WE NEED TO LEARN WHAT REACT DEVELOPERS NEED TO LEARN ABOUT STATE : 👋 State is the most important concept in React ( So we will keep learning about state throughout the entire course…) This section
  • 75. Data Appearance Logic Component Props Data WHAT IS STATE? STATE 👉 Data that a component can hold over time, necessary for information that it needs to remember throughout the app’s lifecycle State Parent Component 👉 “Component’s memory” 🧠
  • 76. WHAT IS STATE? STATE 👉 Data that a component can hold over time, necessary for information that it needs to remember throughout the app’s lifecycle 👉 “Component’s memory” 🧠 👉 “State variable” / “piece of state” : A single variable in a component (component state) We use these terms interchangeably
  • 77. WHAT IS STATE? STATE 👉 Data that a component can hold over time, necessary for information that it needs to remember throughout the app’s lifecycle 👉 Updating component state triggers React to re-render the component Data Appearance Logic Component Props Data State Parent Component 👉 “Component’s memory” 🧠 Component rendered in the UI Component View 👉 Component state: Single local component variable (“Piece of state”, “state variable”) DATA UI State
  • 78. WHAT IS STATE? STATE 1 Update the component’s view (by re-rendering it) 2 Persist local variables between renders STATE ALLOWS DEVELOPERS TO : 👋 State is a tool. Mastering state will unlock the power of React development 👉 Data that a component can hold over time, necessary for information that it needs to remember throughout the app’s lifecycle 👉 Updating component state triggers React to re-render the component 👉 “Component’s memory” 🧠 👉 Component state: Single local component variable (“Piece of state”, “state variable”)
  • 80. SECTION LECTURE STATE, EVENTS, AND FORMS : INTERACTIVE COMPONENTS THE MECHANICS OF STATE
  • 81. THE MECHANICS OF STATE IN REACT We don’t do direct DOM manipulations How is a component view updated then? In React, a view is updated by re-rendering the component Because React is declarative VIEW RENDER / RE - RENDER UPDATED VIEW A component is re-rendered when its state is updated STATE Important React principle 👉 State is preserved throughout re-renders React calls the component function again
  • 82. We don’t do direct DOM manipulations How is a component view updated then? In React, a view is updated by re-rendering the component A component is re-rendered when its state is updated VIEW 3 RE - RENDER RENDER / RE - RENDER STATE UPDATED VIEW Event handler 1 UPDATED STATE UPDATE STATE 2 THE MECHANICS OF STATE IN REACT
  • 83. We don’t do direct DOM manipulations In React, a view is updated by re-rendering the component How is a component view updated then? A component is re-rendered when its state is updated RE - RENDER UPDATE STATE THE MECHANICS OF STATE IN REACT So to update a view, we update state
  • 84. We don’t do direct DOM manipulations In React, a view is updated by re-rendering the component How is a component view updated then? A component is re-rendered when its state is updated THE MECHANICS OF STATE IN REACT So to update a view, we update state REACT REACTS TO STATE CHANGES BY RE - RENDERING THE UI 👉 React is called “React” because... DATA UI
  • 86. SECTION LECTURE STATE, EVENTS, AND FORMS : INTERACTIVE COMPONENTS MORE THOUGHTS ABOUT STATE + STATE GUIDELINES
  • 87. 0 ONE COMPONENT, ONE STATE Counter Multiple instances of the Counter component Counter Counter TeamScores score = 0 score = 0 score = 0 0 0 1 2 score = 1 score = 2 score = 1 1 👋 Each component has and manages its own state, no matter how many times we render the same component
  • 88. DECLARATIVE, REVISITED UI AS A FUNCTION OF STATE UI = TIME STATE UI 👉 With state, we view UI as a reflection of data changing over time 👉 We describe that reflection of data using state, event handlers, and JSX f(state ) Component A Component D Component B Component C
  • 89. 🎯 IN PRACTICAL TERMS... 👉 Example: A modal window can be open or closed. So we create a state variable isOpen that tracks whether the modal is open or not. On isOpen = true we display the window, on isOpen = false we hide it. 👉 If you want to change the way a component looks, or the data it displays, update its state. This usually happens in an event handler function. 👉 Whenever you want something in the component to be dynamic, create a piece of state related to that “thing”, and update the state when the “thing” should change (aka “be dynamic”) 👉 Use a state variable for any data that the component should keep track of (“remember”) over time. This is data that will change at some point. In Vanilla JS, that’s a let variable, or an [] or {} 👉 For data that should not trigger component re-renders, don’t use state. Use a regular variable instead. This is a common beginner mistake. PRACTICAL GUIDELINES ABOUT STATE 👉 When building a component, imagine its view as a reflection of state changing over time
  • 91. SECTION LECTURE STATE, EVENTS, AND FORMS : INTERACTIVE COMPONENTS STATE VS. PROPS
  • 92. STATE VS. PROPS STATE PROPS 👉 Internal data, owned by component 👉 Component “memory” 👉 Can be updated by the component itself 👉 Updating state causes component to re-render 👉 Used to make components interactive 👉 External data, owned by parent component 👉 Similar to function parameters 👉 Read-only 👉 Receiving new props causes component to re-render. Usually when the parent’s state has been updated 👉 Used by parent to configure child component (“settings”) Parent state update
  • 96. THINKING IN REACT “THINKING IN REACT” IS A CORE SKILL HOW TO WORK WITH REACT API THINKING IN REACT This is where professional React apps are built 👉 “React Mindset” 👉 Thinking about components, state, data flow, effects, etc. 👉 Thinking in state transitions, not element mutations
  • 97. State management WHEN YOU KNOW HOW TO “THINK IN REACT”, YOU WILL BE ABLE TO ANSWER : “THINKING IN REACT” AS A PROCESS 🤔 How to break up a UI design into components? 🤔 How to make some components reusable? 🤔 How to assemble UI from reusable components? 🤔 What pieces of state do I need for interactivity? 🤔 Where to place state? ( What component should "own" each piece of state? ) 🤔 What types of state can or should I use? 🤔 How to make data flow through app? Break the desired UI into components and establish the component tree 1 THE “THINKING IN REACT” PROCESS : 2 Build a static version in React (without state) 👉 When to use state 👉 Types of state: local vs. global 👉 Where to place each piece of state 3 Think about state: 4 Establish data flow: 👉 One-way data flow 👉 Child-to-parent communication 👉 Accessing global state Not a rigid process
  • 100. WHAT IS STATE MANAGEMENT? language searchQuery shoppingCart user isOpen coupons notifications 👉 State management: Deciding when to create pieces of state, what types of state are necessary, where to place each piece of state, and how data flows through the app 🏠 Giving each piece of state a home PIECES OF STATE (useState)
  • 101. TYPES OF STATE : LOCAL VS. GLOBAL STATE LOCAL STATE GLOBAL STATE Context API 👉 State needed only by one or few components 👉 State that is defined in a component and only that component and child components have access to it (by passing via props) ☝ We should always start with local state 👉 State that many components might need 👉 Shared state that is accessible to every component in the entire application Global state Local state
  • 102. STATE : WHEN AND WHERE? Need to store data Will data change at some point? Only used by this component? WHERE TO PLACE STATE WHEN TO CREATE STATE Can be computed from existing state/props? YES Regular const variable NO Should it re-render component? NO Place a new piece of state in component YES Derive state YES Ref (useRef, more on this later) NO Also used by a child component? NO Used by one or a few sibling components? NO 👉 Probably global state. Global state management later in the course... NO Leave in component YES Pass to child via props YES Lift state up to first common parent YES “Always start with local state”
  • 105. PROBLEM : SHARING STATE WITH SIBLING COMPONENT Total Checkout Total Promotions coupons ONE - WAY DATA FLOW 🤔 How do we share state with other components? coupons 👉 Total component also needs access to coupons state Promotions coupons setCoupons Data can only flow down to children (via props), not sideways to siblings coupons
  • 106. SOLUTION : LIFTING STATE UP Promotions Total Checkout Total coupons coupons ONE - WAY DATA FLOW coupons coupons setCoupons props props Promotions coupons ✌ By lifting state up, we have successfully shared one piece of state with multiple components in different positions in the component tree State was lifted up to the closest common parent 👉 Total component also needs access to coupons state
  • 107. CHILD - TO - PARENT COMMUNICATION Promotions Total Checkout Total coupons coupons 👉 Total component also needs access to coupons state ONE - WAY DATA FLOW coupons coupons props props Promotions coupons 🤔 If data flows from parent to children, how can Promotions (child) update state in Checkout (parent)? setCoupons setCoupons UPDATE 👉 Child-to-parent communication (inverse data flow): child updating parent state (data “flowing” up)
  • 110. DERIVING STATE DERIVING STATE 👎 Three separate pieces of state, even though numItems and totalPrice depend on cart 👎 Need to keep them in sync (update together) 👎 3 state updates will cause 3 re-renders 👍 Derived state: state that is computed from an existing piece of state or from props 👍 Just regular variables, no useState 👍 cart state is the single source of truth for this related data 👍 Works because re-rendering component will automatically re-calculate derived state
  • 112. SECTION LECTURE THINKING IN REACT : STATE MANAGEMENT THE CHILDREN PROP : MAKING A REUSABLE BUTTON
  • 113. Children of Button, accessible through props.children THE CHILDREN PROP Button 👉 The children prop allow us to pass JSX into an element (besides regular props) 👉 Essential tool to make reusable and configurable components (especially component content) 👉 Really useful for generic components that don’t know their content before being used (e.g. modal) props.children An empty “hole” that can be filled by any JSX the component receives as children
  • 117. SECTION LECTURE THINKING IN REACT : COMPONENTS, COMPOSITION, AND REUSABILITY HOW TO SPLIT A UI INTO COMPONENTS
  • 118. COMPONENT SIZE MATTERS COMPONENT SIZE 👉 Too many responsibilities 👉 Might need too many props 👉 Hard to reuse 👉 Complex code, hard to understand SMALL HUGE Just one huge component
  • 119. COMPONENT SIZE MATTERS COMPONENT SIZE 👉 We end up with 100s of mini-components 👉 Confusing codebase 👉 Too abstracted SMALL HUGE 0 0 0 Many small components Generally, we need to find the right balance between too specific and too broad 👉 Too many responsibilities 👉 Might need too many props 👉 Hard to reuse 👉 Complex code, hard to understand Creating something new to hide the implementation details of that thing
  • 120. HOW TO SPLIT A UI INTO COMPONENTS 0 0 0 0 0 3. Responsibilities / complexity 2. Reusability 4. Personal coding style 1.Logical separation of content/layout 👉 The 4 criteria for splitting a UI into components: ✅ Logical separation ✅ Some are reusable ✅ Low complexity 👎 👎
  • 121. FRAMEWORK : WHEN TO CREATE A NEW COMPONENT? 👉 Is it possible to reuse part of the component? 👉 Do you want or need to reuse it? 👉 Is the component doing too many different things? 👉 Does the component rely on too many props? 👉 Does the component have too many pieces of state and/or effects? 👉 Is the code, including JSX, too complex/confusing? 👉 Do you prefer smaller functions/components? 💡 SUGGESTION : When in doubt, start with a relatively big component, then split it into smaller components as it becomes necessary You might need a new component Skip if you're sure you need to reuse. But otherwise, you don’t need to focus on reusability and complexity early on 3. Responsibilities / complexity 2. Reusability 4. Personal coding style 👉 Does the component contain pieces of content or layout that don’t belong together? 1.Logical separation of content/layout 👋 These are all guidelines… It will become intuitive over time!
  • 122. SOME MORE GENERAL GUIDELINES 💰 Be aware that creating a new component creates a new abstraction. Abstractions have a cost, because more abstractions require more mental energy to switch back and forth between components. So try not to create new components too early 🏷 Name a component according to what it does or what it displays. Don’t be afraid of using long component names 🪆 Never declare a new component inside another component! 🗃 Co-locate related components inside the same file. Don’t separate components into different files too early ↔ It’s completely normal that an app has components of many different sizes, including very small and huge ones ( See next slide... 👉)
  • 123. 0 0 ANY APP HAS COMPONENTS OF DIFFERENT SIZES AND REUSABILITY SMALL HUGE Components with all different sizes 👉 Some very small components are necessary! 👉 Highly reusable 👉 Very low complexity 👉 Most apps will have a few huge components 👉 Not meant to be reused (not a problem! ) 👉 Page component REUSABLE NON - REUSABLE Different degrees of size, reusability, responsibility, and complexity
  • 125. SECTION LECTURE THINKING IN REACT : COMPONENTS, COMPOSITION, AND REUSABILITY COMPONENT CATEGORIES
  • 126. COMPONENT CATEGORIES 👉 Most of your components will naturally fall into one of three categories: Stateful components Stateless / presentational components Structural components 👉 No state 👉 Can receive props and simply present received data or other content 👉 Usually small and reusable 👉 Have state 👉 Can still be reusable 👉 “Pages”, “layouts”, or “screens” of the app 👉 Result of composition 👉 Can be huge and non- reusable (but don’t have to)
  • 128. SECTION LECTURE THINKING IN REACT : COMPONENTS, COMPOSITION, AND REUSABILITY COMPONENT COMPOSITION
  • 129. “USING” A COMPONENT WHAT IS COMPONENT COMPOSITION? Modal COMPONENT COMPOSITION 👉 Success is inside Modal: we can NOT reuse Modal Modal Success 👉 Success is passed into Modal: we can REUSE Modal Success Want to reuse
  • 130. WHAT IS COMPONENT COMPOSITION? COMPONENT COMPOSITION Modal Error 👉 Success is passed into Modal: we can REUSE Modal 👉 Component composition: combining different components using the children prop (or explicitly defined props) Create highly reusable and flexible components 1 2 Fix prop drilling (great for layouts) WE COMPONENT COMPOSITION, WE CAN : Possible because components don’t need to know their children in advance
  • 132. SECTION LECTURE THINKING IN REACT : COMPONENTS, COMPOSITION, AND REUSABILITY PROPS AS A COMPONENT API
  • 133. TOO LITTLE PROPS PROPS AS AN API 👉 Too hard to use 👉 Exposing too much complexity 👉 Hard-to-write code 👉 Provide good default values 👉 Not flexible enough 👉 Might not be useful TOO MANY PROPS 👩💻 COMPONENT CONSUMER 🧑💻 COMPONENT CREATOR We need to find the right balance between too little and too many props, that works for both the consumer and the creator 🎛 Component props = Public API Consuming component App 👩💻 Component Abstraction that encapsulates UI and logic
  • 134. GOT QUESTIONS? FEEDBACK? JUST POST IT IN THE Q&A OF THIS VIDEO, AND YOU WILL GET HELP THERE!
  • 136. HOW REACT WORKS BEHIND THE SCENES
  • 137. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES COMPONENTS, INSTANCES, AND ELEMENTS
  • 138. COMPONENT VS. INSTANCE VS. ELEMENT Component 👉 Description of a piece of UI 👉 A component is a function that returns React elements (element tree), usually written as JSX 👉 “Blueprint” or “Template”
  • 139. COMPONENT VS. INSTANCE VS. ELEMENT Component Component Instance 👉 Instances are created when we “use” components 👉 React internally calls Tab() 👉 Actual “physical” manifestation of a component 👉 Has its own state and props 👉 Has a lifecycle (can “be born”, “live”, and “die”) Instances of Tab
  • 140. COMPONENT VS. INSTANCE VS. ELEMENT Component Component Instance React Element RETURNS 👉 JSX is converted to React.createElement() function calls 👉 A React element is the result of these function calls 👉 Information necessary to create DOM elements REACT ELEMENT
  • 141. COMPONENT VS. INSTANCE VS. ELEMENT Component Component Instance React Element RETURNS DOM Element ( HTML ) INSERTED TO DOM 👉 Actual visual representation of the component instance in the browser
  • 143. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES HOW RENDERING WORKS : OVERVIEW
  • 144. QUICK RECAP BEFORE WE GET STARTED User Interface on the screen Component A Component B React Element React Element React Element React Element DOM Element ( HTML ) DOM Element ( HTML ) DOM Element ( HTML ) DOM Element ( HTML ) Component Instance A2 Component Instance A1 Component Instance A3 . . . Component Instance B1 . . . 🤔 How does this process actually work?
  • 145. OVERVIEW : HOW COMPONENTS ARE DISPLAYED ON THE SCREEN RENDER IS TRIGGERED RENDER PHASE COMMIT PHASE BROWSER PAINT ☝ In React, rendering is NOT updating the DOM or displaying elements on the screen. Rendering only happens internally inside React, it does not produce visual changes. Common sense meaning of the word “render” By updating state somewhere React calls component functions and figures out how DOM should be updated React actually writes to the DOM, updating, inserting, and deleting elements
  • 146. THE TWO SITUATIONS THAT TRIGGER RENDERS : HOW RENDERS ARE TRIGGERED [ 1 ] RENDER IS TRIGGERED 👉 In practice, it looks like React only re-renders the component where the state update happens, but that’s not how it works behind the scenes 👉 Renders are not triggered immediately, but scheduled for when the JS engine has some “free time”. There is also batching of multiple setState calls in event handlers Initial render of the application 1 2 State is updated in one or more component instances (re-render) 👉 The render process is triggered for the entire application
  • 148. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES HOW RENDERING WORKS : THE RENDER PHASE
  • 149. VIEW 3 RE - RENDER RENDER / RE - RENDER STATE UPDATED VIEW Event handler 1 UPDATED STATE UPDATE STATE 2 REVIEW : THE MECHANICS OF STATE IN REACT NOT TRUE #1 : RENDERING IS UPDATING THE SCREEN / DOM NOT TRUE #2 : REACT COMPLETELY DISCARDS OLD VIEW ( DOM ) ON RE - RENDER
  • 150. THE RENDER PHASE [ 2 ] RENDER PHASE Component instances that triggered re-render New Virtual DOM React Elements
  • 151. C COMPONENT TREE B A D E E C COMPONENT TREE B A E E D STATE UPDATE C REACT ELEMENT TREE B A D E E THE VIRTUAL DOM ( REACT ELEMENT TREE ) 1⃣ INITIAL RENDER C REACT ELEMENT TREE B A D E E D E E “Virtual DOM” 👉 Virtual DOM : Tree of all React elements created from all instances in the component tree 👉 Cheap and fast to create multiple trees 👉 Nothing to do with “shadow DOM” 🔄 RE - RENDERS 🚨 Rendering a component will cause all of its child components to be rendered as well (no matter if props changed or not)
  • 152. C COMPONENT TREE B A D E E C COMPONENT TREE B A E E D STATE UPDATE C REACT ELEMENT TREE B A D E E THE VIRTUAL DOM ( REACT ELEMENT TREE ) 1⃣ INITIAL RENDER C REACT ELEMENT TREE B A D E E A “Virtual DOM” 👉 Virtual DOM : Tree of all React elements created from all instances in the component tree 👉 Cheap and fast to create multiple trees 👉 Nothing to do with “shadow DOM” 🔄 RE - RENDERS 🚨 Rendering a component will cause all of its child components to be rendered as well (no matter if props changed or not) 👉 Necessary because React doesn’t know whether children will be affected
  • 153. THE RENDER PHASE [ 2 ] RENDER PHASE Component instances that triggered re-render New Virtual DOM Current Fiber tree (before state update) Updated Fiber tree React Elements Reconciler called “Fiber” Reconciliation + Diffing
  • 154. WHAT IS RECONCILIATION AND WHY DO WE NEED IT? 🤔 Why not update the entire DOM whenever state changes somewhere in the app? showModal = true 👉 That would be inefficient and wasteful: 👉 React reuses as much of the existing DOM as possible ❤ Reconciliation: Deciding which DOM elements actually need to be inserted, deleted, or updated, in order to reflect the latest state changes Writing to the DOM is (relatively) slow 1 2 Usually only a small part of the DOM needs to be updated BECAUSE HOW? Only these new DOM elements are created
  • 155. Current state Props Side effects Used hooks FIBER Modal Video Btn Overlay h3 button App FIBER TREE ON INITIAL RENDER THE RECONCILER : FIBER REACT ELEMENT TREE ( VIRTUAL DOM ) Modal Video Btn App Overlay h3 button 👉 Fiber tree: internal tree that has a “fiber” for each component instance and DOM element 👉 Fibers are NOT re-created on every render 👉 Work can be done asynchronously Queue of work “Unit of work” 👉 Rendering process can be split into chunks, tasks can be prioritized, and work can be paused, reused, or thrown away 👉 Enables concurrent features like Suspense or transitions 👉 Long renders won’t block JS engine
  • 156. UPDATED FIBER TREE Modal Video Btn Overlay h3 button App ( Showing DOM work) App Video Btn NEW VIRTUAL DOM RECONCILIATION IN ACTION Modal Video Btn App Overlay h3 button showModal = true Modal Video Btn Overlay h3 button App CURRENT FIBER TREE showModal = false STATE UPDATE DOM Deletions DOM Update (text) State update in App, so all remaining children are re-rendered Reconciliation + Diffing (workInProgress) Comparing elements based on their position in the tree
  • 157. THE RENDER PHASE [ 2 ] RENDER PHASE Component instances that triggered re-render New Virtual DOM Updated Fiber tree List of DOM updates React Elements Result of the render phase (“list of effects”) Reconciler called “Fiber” Reconciliation + Diffing Current Fiber tree (before state update)
  • 159. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES HOW RENDERING WORKS : THE COMMIT PHASE
  • 160. THE COMMIT PHASE AND BROWSER PAINT [ 3 ] COMMIT PHASE [ 4 ] BROWSER PAINT Updated DOM List of DOM updates [ 2 ] RENDER PHASE Updated UI on the screen React React 👉 React writes to the DOM : insertions, deletions, and updates (list of DOM updates are “flushed” to the DOM ) 👉 Committing is synchronous: DOM is updated in one go, it can’t be interrupted. This is necessary so that the DOM never shows partial results, ensuring a consistent UI (in sync with state at all times) 👉 After the commit phase completes, the workInProgress fiber tree becomes the current tree for the next render cycle DOM
  • 161. THE COMMIT PHASE AND BROWSER PAINT [ 3 ] COMMIT PHASE [ 4 ] BROWSER PAINT Updated DOM Updated UI on the screen React ReactDOM Does not touch the DOM. React only renders. It doesn’t know where the render result will go React Native Many others… React can be used on different platforms (“hosts”) “RENDERERS” Terrible name! Renderers do not render, they commit the result of render phase… List of DOM updates [ 2 ] RENDER PHASE
  • 162. [ 4 ] BROWSER PAINT [ 3 ] COMMIT PHASE [ 2 ] RENDER PHASE RECAP : PUTTING IT ALL TOGETHER List of DOM updates Updated UI on screen Updated Fiber tree Current Fiber tree Reconciliation + Diffing [ 1 ] TRIGGER 💥 Updated DOM New Virtual DOM Updated React Elements 👉 Does not produce any visual output 👉 Rendering a component also renders all of its child components 👉 Asynchronous: work can be split, prioritized, paused, resumed 👉 Happens only on initial render and state updates 👉 Synchronous: DOM updates are written in one go, to keep UI consistent
  • 164. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES HOW DIFFING WORKS
  • 165. THE RENDER PHASE [ 2 ] RENDER PHASE Component instances that triggered re-render New Virtual DOM Updated Fiber tree List of DOM updates React Elements Reconciliation + Diffing Current Fiber tree (before state update) Comparing elements step- by-step, based on their position in the tree
  • 166. HOW DIFFING WORKS 👉 Diffing uses 2 fundamental assumptions (rules): Two elements of different types will produce different trees 1 2 Elements with a stable key prop stay the same across renders 👉 This allows React to go from 1,000,000,000 [ O(n3)] to 1000 [O(n)] operations per 1000 elements 1. SAME POSITION, DIFFERENT ELEMENT 👉 React assumes entire sub-tree is no longer valid 👉 Old components are destroyed and removed from DOM, including state 👉 Tree might be rebuilt if children stayed the same (state is reset) Different DOM element Different React element (component instance)
  • 167. HOW DIFFING WORKS 2. SAME POSITION, SAME ELEMENT 👉 Diffing uses 2 fundamental assumptions (rules): Two elements of different types will produce different trees 1 2 Elements with a stable key prop stay the same across renders 👉 Element will be kept (as well as child elements), including state 👉 New props / attributes are passed if they changed between renders 👉 Sometimes this is not what we want… Then we can use the key prop Same DOM element Same React element (component instance) 👉 This allows React to go from 1,000,000,000 [ O(n3)] to 1000 [O(n)] operations per 1000 elements
  • 169. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES THE KEY PROP
  • 170. WHAT IS THE KEY PROP? KEY PROP 👉 Special prop that we use to tell the diffing algorithm that an element is unique 👉 Allows React to distinguish between multiple instances of the same component type 👉 When a key stays the same across renders, the element will be kept in the DOM (even if the position in the tree changes) 👉 When a key changes between renders, the element will be destroyed and a new one will be created (even if the position in the tree is the same as before) Using keys in lists 1 2 Using keys to reset state
  • 171. 👍 WITH KEYS ADDING NEW LIST ITEM ADDING NEW LIST ITEM 1. KEYS IN LISTS [ STABLE KEY ] 👎 NO KEYS 👉 Same elements, but different position in tree, so they are removed and recreated in the DOM (bad for performance) 👉 Different position in the tree, but the key stays the same, so the elements will be kept in the DOM 👉 Always use keys!
  • 172. 2. KEY PROP TO RESET STATE [ CHANGING KEY ] 👉 If we have the same element at the same position in the tree, the DOM element and state will be kept Question state (answer): State was preserved. NOT what we want Question state (answer): NEW QUESTION IN SAME POSITION
  • 173. 2. KEY PROP TO RESET STATE [ CHANGING KEY ] 👉 If we have the same element at the same position in the tree, the DOM element and state will be kept Question state (answer): NEW QUESTION IN SAME POSITION Question state (answer): State was RESET 👍 WITH KEY
  • 175. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES RULES FOR RENDER LOGIC : PURE COMPONENTS
  • 176. 2. EVENT HANDLER FUNCTIONS THE TWO TYPES OF LOGIC IN REACT COMPONENTS 1. RENDER LOGIC 👉 Code that lives at the top level of the component function 👉 Participates in describing how the component view looks like 👉 Executed every time the component renders 👉 Executed as a consequence of the event that the handler is listening for (change event in this example) 👉 Code that actually does things: update state, perform an HTTP request, read an input field, navigate to another page, etc.
  • 177. REFRESHER : FUNCTIONAL PROGRAMMING PRINCIPLES 👉 Side effect: dependency on or modification of any data outside the function scope. “Interaction with the outside world”. Examples: mutating external variables, HTTP requests, writing to DOM. 👉 Pure function: a function that has no side effects. 👉 Does not change any variables outside its scope 👉 Given the same input, a pure function always returns the same output 👋 Side effects are not bad! A program can only be useful if it has some interaction with the outside world ✅ Pure function ☝ Impure function ☝ Impure function Side effect: Outside variable mutation Unpredictable output (date changes)
  • 178. RULES FOR RENDER LOGIC 👋 Side effects are allowed (and encouraged) in event handler functions! There is also a special hook to register side effects (useEffect) ☝ Components must be pure when it comes to render logic: given the same props (input), a component instance should always return the same JSX (output) ☝ Render logic must produce no side effects: no interaction with the “outside world” is allowed. So, in render logic: 👉 Do NOT perform network requests ( API calls) 👉 Do NOT start timers 👉 Do NOT directly use the DOM API 👉 Do NOT mutate objects or variables outside of the function scope 👉 Do NOT update state (or refs): this will create an infinite loop! This is why we can’t mutate props!
  • 180. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES STATE UPDATE BATCHING
  • 181. HOW STATE UPDATES ARE BATCHED 👉 Renders are not triggered immediately, but scheduled for when the JS engine has some “free time”. There is also batching of multiple setState calls in event handlers Event handler function
  • 182. HOW STATE UPDATES ARE BATCHED answer = '' NEW STATE RENDER + COMMIT best = true RENDER + COMMIT solved = false RENDER + COMMIT EVENT HANDLER FUNCTION This is NOT how React updates multiple pieces of state in the same event handler
  • 183. HOW STATE UPDATES ARE BATCHED answer = '' best = true solved = false NEW STATE RENDER + COMMIT EVENT HANDLER FUNCTION Batched state update Just ONE render and commit per event handler No wasted renders, better for performance
  • 184. UPDATING STATE IS ASYNCHRONOUS EVENT HANDLER FUNCTION 🤔 🤔 What will the value of answer be at this point? State is stored in the Fiber tree during render phase At this point, re-render has not happened yet Therefore, answer still contains current state, not the updated state ('') UPDATING STATE IN REACT IS ASYNCHRONOUS 👉 Updated state variables are not immediately available after setState call, but only after the re-render 👉 This also applies when only one state variable is updated 👉 If we need to update state based on previous update, we use setState with callback (setAnswer(answer=>...)) “Stale state”
  • 185. BATCHING BEYOND EVENT HANDLER FUNCTIONS EVENT HANDLERS TIMEOUTS PROMISES NATIVE EVENTS REACT 17 REACT 18 + ✅ ✅ ✅ ✅ ✅ ❌ ❌ ❌ 👉 AUTOMATIC BATCHING IN... 👉 We can opt out of automatic batching by wrapping a state update in ReactDOM.flushSync() (but you will never need this) We now get automatic batching at all times, everywhere
  • 187. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES HOW EVENTS WORK IN REACT
  • 188. EVENT DELEGATION DOM REFRESHER : EVENT PROPAGATION AND DELEGATION DOCUMENT <html> <body> <button> .btn <div> .options <header> .topbar <div> #root <button> .btn <button> .btn 1 CAPTURING PHASE 2 TARGET ELEMENT 3 BUBBLING PHASE DOM tree (not Fiber tree or React element tree) 👉 Handling events for multiple elements centrally in one single parent element 👉 Better for performance and memory, as it needs only one handler function 👋 Very common in vanilla JS apps, but not so much in React apps 2 Check for target element (e.target) 3 If target is one of the <button>s, handle the event Add handler to parent (.options) 1 👉 By default, event handlers listen to events on the target and during the bubbling phase 👉 We can prevent bubbling with e.stopPropagation() H H EVENT H H
  • 189. DOCUMENT <html> <body> <button> .btn <div> .options <header> .topbar <div> #root <button> .btn <button> .btn HOW REACT HANDLES EVENTS WHEN WE ATTACH AN EVENT HANDLER... 👉 Behind the scenes, React performs event delegation for all events in our applications React registers all event handlers on the root DOM container. This is where all events are handled Usually div#root, but can be any DOM element ✅ ... WHAT ACTUALLY HAPPENS INTERNALLY ⛔ ... WHAT APPEARS TO BE HAPPENING INSIDE REACT FIBER TREE H H
  • 190. SyntheticEvent SYNTHETIC EVENTS PointerEvent MouseEvent KeyboardEvent ... 👉 Wrapper around the DOM’s native event object 👉 Has same interface as native event objects, like stopPropagation() and preventDefault() 👉 Fixes browser inconsistencies, so that events work in the exact same way in all browsers 👉 Most synthetic events bubble (including focus, blur, and change), except for scroll 👉 Attributes for event handlers are named using camelCase (onClick instead of onclick or click) 👉 Default behavior can not be prevented by returning false (only by using preventDefault()) 👉 Attach “Capture” if you need to handle during capture phase (example: onClickCapture) EVENT HANDLERS IN VS.
  • 192. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES LIBRARIES VS. FRAMEWORKS & THE REACT ECOSYSTEM
  • 193. FIRST, AN ANALOGY 🍣 👍 Ease of mind: All ingredients are included 👎 No choice: You’re stuck with the kit’s ingredients ALL - IN - ONE KIT SEPARATE INGREDIENTS 👍 Freedom: You can choose the best ingredients 👎 Decision fatigue: You need to research and buy all ingredients separately
  • 194. FIRST, AN ANALOGY 🍣 👍 Ease of mind: All ingredients are included 👎 No choice: You’re stuck with the kit’s ingredients ALL - IN - ONE KIT SEPARATE INGREDIENTS 👍 Freedom: You can choose the best ingredients 👎 Decision fatigue: You need to research and buy all ingredients separately
  • 195. FRAMEWORK VS. LIBRARY 👍 Ease of mind: Everything you need to build a complete application is included in the framework (“batteries included”) 👎 No choice: You’re stuck with the framework’s tools and conventions (which is not always bad! ) FRAMEWORK LIBRARY 👍 Freedom: You can (or need to) choose multiple 3rd-party libraries to build a complete application 👎 Decision fatigue: You need to research, download, learn, and stay up-to-date with multiple external libraries “Separate ingredients” “All-in-one kit” Routing HTTP requests Styling Form management LARGE - SCALE REACT APP External libraries “View” library Routing HTTP requests Styling Form management LARGE - SCALE ANGULAR APP Frameworks include everything
  • 196. 1 Routing (for SPAs) 2 HTTP requests 3 Remote state management 4 Global state management 5 Styling 6 Form management 7 Animations/transitions 8 UI components REACT 3RD - PARTY LIBRARY ECOSYSTEM fetch() Context API Zustand 👉 Library options for different React application needs
  • 197. FRAMEWORKS BUILT ON TOP OF REACT “Opinionated” React frameworks Routing HTTP requests Styling Form management “VANILLA” REACT APP External libraries Routing HTTP requests Styling Form management Included out of the box 👉 React frameworks offer many other features: server-side rendering ( SSR ) , static site generation ( SSG ) , better developer experience ( DX ) , etc. Full-stack frameworks!
  • 199. SECTION LECTURE HOW REACT WORKS BEHIND THE SCENES SECTION SUMMARY : PRACTICAL TAKEAWAYS
  • 200. 🧩 A component is like a blueprint for a piece of UI that will eventually exist on the screen. When we “use” a component, React creates a component instance, which is like an actual physical manifestation of a component, containing props, state, and more. A component instance, when rendered, will return a React element ☎ “Rendering” only means calling component functions and calculating what DOM elements need to be inserted, deleted, or updated. It has nothing to do with writing to the DOM. Therefore, each time a component instance is rendered and re-rendered, the function is called again 🔁 Only the initial app render and state updates can cause a render, which happens for the entire application, not just one single component 👪 When a component instance gets re-rendered, all its children will get re-rendered as well. This doesn’t mean that all children will get updated in the DOM, thanks to reconciliation, which checks which elements have actually changed between two renders. But all this re-rendering can still have an impact on performance (more on that later in the course 👉) 🎯 PRACTICAL SUMMARY
  • 201. 🧬 Diffing is how React decides which DOM elements need to be added or modified. If, between renders, a certain React element stays at the same position in the element tree, the corresponding DOM element and component state will stay the same. If the element changed to a different position, or if it’s a different element type, the DOM element and state will be destroyed 🔑 Giving elements a key prop allows React to distinguish between multiple component instances. When a key stays the same across renders, the element is kept in the DOM. This is why we need to use keys in lists. When we change the key between renders, the DOM element will be destroyed and rebuilt. We use this as a trick to reset state 🪆 Never declare a new component inside another component! Doing so will re-create the nested component every time the parent component re-renders. React will always see the nested component as new, and therefore reset its state each time the parent state is updated 🔮 The logic that produces JSX output for a component instance (“render logic”) is not allowed to produce any side effects: no API calls, no timers, no object or variable mutations, no state updates. Side effects are allowed in event handlers and useEffect (next section 👉) 🎯 PRACTICAL SUMMARY
  • 202. 📱 The DOM is updated in the commit phase, but not by React, but by a “renderer” called ReactDOM. That’s why we always need to include both libraries in a React web app project. We can use other renderers to use React on different platforms, for example to build mobile or native apps 🗂 Multiple state updates inside an event handler function are batched, so they happen all at once, causing only one re-render. This means we can not access a state variable immediately after updating it: state updates are asynchronous. Since React 18, batching also happens in timeouts, promises, and native event handlers. 🌐 When using events in event handlers, we get access to a synthetic event object, not the browser’s native object, so that events work the same way across all browsers. The difference is that most synthetic events bubble, including focus, blur, and change, which do not bubble as native browser events. Only the scroll event does not bubble 🛠 React is a library, not a framework. This means that you can assemble your application using your favorite third-party libraries. The downside is that you need to find and learn all these additional libraries. No problem, as you will learn about the most commonly used libraries in this course 🎯 PRACTICAL SUMMARY
  • 205. SECTION LECTURE EFFECTS AND DATA FETCHING THE COMPONENT LIFECYCLE
  • 206. COMPONENT ( INSTANCE ) LIFECYCLE 👉 Component instance is rendered for the first time 👉 Fresh state and props are created 💀 🐣 🐓 MOUNT / INITIAL RENDER UNMOUNT 👉 Component instance is destroyed and removed 👉 State and props are destroyed HAPPENS WHEN : 👉 State changes 👉 Props change 👉 Parent re-renders 👉 Context changes RE - RENDER 👋 We can define code to run at these specific points in time ( Optional)
  • 208. SECTION LECTURE EFFECTS AND DATA FETCHING A FIRST LOOK AT EFFECTS
  • 209. WHERE TO CREATE SIDE EFFECTS SIDE EFFECT Triggered by EVENTS : onClick, onSubmit, etc. Triggered by RENDERING EVENT HANDLERS EFFECTS (useEffect) 👉 Effects allow us to write code that will run at different moments: mount, re- render, or unmount Sometimes this is not enough for the application’s needs (can be made in...) We need side effects all the time. They make our applications do something. Not in render logic! 👉 REVIEW : A side effect is basically any “interaction between a React component and the world outside the component”. We can also think of a side as “code that actually does something”. Examples: Data fetching, setting up subscriptions, setting up timers, manually accessing the DOM, etc.
  • 210. EVENT HANDLERS VS. EFFECTS EVENT HANDLERS EFFECTS ( useEffect) 👉 Executed when the corresponding event happens 👉 Used to react to an event 👉 Executed after the component mounts (initial render), and after subsequent re-renders (according to dependency array) 👉 Used to keep a component synchronized with some external system (in this example, with the API movie data) Produce the same result, but at different moments ( We’ll come back to all this after using useEffect in practice...) ☝ Preferred way of creating side effects! Effect Cleanup function Thinking about synchronization, not lifecycles Dependency array 🤔 When?
  • 212. SECTION LECTURE EFFECTS AND DATA FETCHING THE USEEFFECT DEPENDENCY ARRAY
  • 213. WHAT’S THE USEEFFECT DEPENDENCY ARRAY? 👉 By default, effects run after every render. We can prevent that by passing a dependency array 👉 Without the dependency array, React doesn’t know when to run the effect 👉 Each time one of the dependencies changes, the effect will be executed again ☝ Every state variable and prop used inside the effect MUST be included in the dependency array THE DEPENDENCY ARRAY Otherwise, we get a “stale closure”. We will go more into depth in a future section 👉
  • 214. USEEFFECT IS A SYNCHRONIZATION MECHANISM title CHANGES userRating CHANGES COMPONENT STATE/PROPS EFFECT IS EXECUTED AGAIN EXTERNAL SYSTEM ( SIDE EFFECT ) SYNCHRONIZE WITH DOCUMENT TITLE IS UPDATED DEPENDENCIES 👉 useEffect is like an event listener that is listening for one dependency to change. Whenever a dependency changes, it will execute the effect again 👉 Effects react to updates to state and props used inside the effect (the dependencies). So effects are “reactive” (like state updates re-rendering the UI ) THE MECHANICS OF EFFECTS
  • 215. SYNCHRONIZATION AND LIFECYCLE 👉 We can use the dependency array to run effects when the component renders or re-renders DEPENDENCY ( STATE OR PROPS ) CHANGES EFFECT IS EXECUTED AGAIN COMPONENT IS RE - RENDERED Effects and component lifecycle are deeply connected Effect synchronizes with x, y, and z Runs on mount and re-renders triggered by updating x, y, or z Effect synchronizes with no state/props Runs only on mount (initial render) Effect synchronizes with everything Runs on every render (usually bad ⛔) 🔄 SYNCHRONIZATION 🐣 LIFECYCLE
  • 216. WHEN ARE EFFECTS EXECUTED? MOUNT ( INITIAL RENDER ) COMMIT BROWSER PAINT EFFECT ✨ RE - RENDER COMMIT LAYOUT EFFECT BROWSER PAINT UNMOUNT title = ‘Interstellar’ title = ‘Interstellar Wars’ title CHANGES EFFECT ✨ time Another type of effect that is very rarely necessary (useLayoutEffect) If an effect sets state, an additional render will be required
  • 218. SECTION LECTURE EFFECTS AND DATA FETCHING THE USEEFFECT CLEANUP FUNCTION
  • 219. CLEANUP 🧹 CLEANUP 🧹 WHEN ARE EFFECTS EXECUTED? MOUNT ( INITIAL RENDER ) COMMIT BROWSER PAINT EFFECT ✨ RE - RENDER COMMIT LAYOUT EFFECT BROWSER PAINT UNMOUNT title = ‘Interstellar’ title = ‘Interstellar Wars’ title CHANGES EFFECT ✨ time
  • 220. THE CLEANUP FUNCTION USEEFFECT CLEANUP FUNCTION 👉 Function that we can return from an effect (optional) 👉 Runs on two different occasions: Before the effect is executed again 1 2 After a component has unmounted Execute effect if dependency array includes updated data COMPONENT RENDERS Execute cleanup function COMPONENT UNMOUNTS 👉 Necessary whenever the side effect keeps happening after the component has been re-rendered or unmounted ☝ Each effect should do only one thing! Use one useEffect hook for each side effect. This makes effects easier to clean up ✨ EFFECT 🧹 POTENTIAL CLEANUP 👉 HTTP request 👉 API subscription 👉 Start timer 👉 Add event listener Cancel request Cancel subscription Stop timer Remove listener Examples
  • 222. CUSTOM HOOKS, REFS, AND MORE STATE
  • 223. SECTION LECTURE CUSTOM HOOKS, REFS, AND MORE STATE REACT HOOKS AND THEIR RULES
  • 224. REACT HOOKS WHAT ARE REACT HOOKS? 👉 Special built-in functions that allow us to “hook” into React internals: 👉 Creating and accessing state from Fiber tree 👉 Registering side effects in Fiber tree 👉 Manual DOM selections 👉 Many more… 👉 Always start with “use” (useState, useEffect, etc.) 👉 Enable easy reusing of non-visual logic: we can compose multiple hooks into our own custom hooks 👉 Give function components the ability to own state and run side effects at different lifecycle points (before v16.8 only available in class components)
  • 225. OVERVIEW OF ALL BUILT - IN HOOKS ✅ useState ✅ useEffect 👉 useReducer 👉 useContext 🥇 MOST USED 👉 useRef 👉 useCallback 👉 useMemo 👉 useTransition 👉 useDeferredValue ❌ useLayoutEffect ❌ useDebugValue ❌ useImperativeHandle ❌ useId 📜 LESS USED ❌ useSyncExternalStore ❌ useInsertionEffect 🗃 ONLY FOR LIBRARIES ✅ Have learned 👉 Will learn ❌ Will not learn 👋 As of React v18.x
  • 226. THE RULES OF HOOKS 👋 These rules are automatically enforced by React’s ESLint rules Only call hooks at the top level 1 2 Only call hooks from React functions ☝ RULES OF HOOKS 👉 Do NOT call hooks inside conditionals, loops, nested functions, or after an early return 👉 This is necessary to ensure that hooks are always called in the same order (hooks rely on this) 👉 Only call hooks inside a function component or a custom hook
  • 227. RENDER ☝ Hypothetical example! This code does NOT work HOOKS RELY ON CALL ORDER State A State B Effect Z REACT ELEMENT TREE FIBER TREE ON INITIAL RENDER List built based on hooks call order A=7 A=23 7 A===23 is now false, so after re- render, this hook would no longer exist, destroying the linked list 😢 false 👉 Hooks need to called in the same order on every render Props FIBER . . . List of hooks Violates Rule #1 LINKED LIST OF USED HOOKS 1 State A 1 3 Effect Z 3 2 State B 2
  • 228. HOOKS RELY ON CALL ORDER State A State B Effect Z State A State B Effect Z 1 3 2 REACT ELEMENT TREE FIBER TREE Props List of hooks FIBER . . . ON INITIAL RENDER LINKED LIST OF USED HOOKS 1 2 3 👍 Correct code! RENDER ☝ Hooks can only be called at top level SAME ORDER List built based on hooks call order 👉 Hooks need to called in the same order on every render Order num uniquely identifies each hook
  • 230. SECTION LECTURE CUSTOM HOOKS, REFS, AND MORE STATE USESTATE SUMMARY
  • 231. 2 UPDATING STATE SUMMARY OF DEFINING AND UPDATING STATE CREATING STATE 1 👉 Function must be pure and accept no arguments. Called only on initial render 👉 Function must be pure and return next state Simple Based on function (lazy evaluation) Simple Based on current state Make sure to NOT mutate objects or arrays, but to replace them
  • 233. SECTION LECTURE CUSTOM HOOKS, REFS, AND MORE STATE INTRODUCING ANOTHER HOOK : USEREF
  • 234. REF WITH useRef WHAT ARE REFS? 👉 “Box” (object) with a mutable .current property that is persisted across renders (“normal” variables are always reset) 👉 Two big use cases: Creating a variable that stays the same between renders (e.g. previous state, setTimeout id, etc.) 1 2 Selecting and storing DOM elements myRef .current (23) (1000) We can write to and read from the ref using .current 👉 Refs are for data that is NOT rendered: usually only appear in event handlers or effects, not in JSX (otherwise use state) ☝ Do NOT read write or read .current in render logic (like state)
  • 235. STATE VS. REFS ❌ STATE REFS UPDATING CAUSES RE - RENDER ✅ IMMUTABLE ✅ ASYNCHRONOUS UPDATES ✅ ✅ PERSISTS ACROSS RENDERS ✅ ❌ ❌ Need to store data Will data change at some point? Regular const variable NO Should it re-render component? YES State (useState) YES Ref (useRef) NO ( Taken from lecture “Fundamentals of state management”) Examples: preserving previous state, or storing the id of a setTimeout
  • 237. SECTION LECTURE CUSTOM HOOKS, REFS, AND MORE STATE WHAT ARE CUSTOM HOOKS? WHEN TO CREATE ONE?
  • 238. REUSING LOGIC WITH CUSTOM HOOKS 👉 “I need to reuse:” Does logic contain any hooks? REGULAR FUNCTION NO CUSTOM HOOK YES COMPONENT UI LOGIC 👉 Allow us to reuse non-visual logic in multiple components 👉 One custom hook should have one purpose, to make it reusable and portable (even across multiple projects) 👉 Rules of hooks apply to custom hooks too Needs to use one or more hooks Unlike components, can receive and return any relevant data (usually [] or {}) Function name needs to start with use
  • 241. SECTION LECTURE REACT BEFORE HOOKS : CLASS - BASED REACT CLASS COMPONENTS VS. FUNCTION COMPONENTS
  • 242. 🏆 Advantages ☎ Event handlers this.setState() this.props.X 🎛 Reading props 🚀 Local state JavaScript function (any type) 💎 How to create FUNCTION COMPONENTS VS. CLASS COMPONENTS 👍 Easier to build (less boilerplate code) 👍 Cleaner code: useEffect combines all lifecycle-related code in a single place 👍 Easier to share stateful logic 👍 We don’t need this keyword anymore 👍 Lifecycle might be easier to understand for beginners FUNCTION COMPONENTS CLASS COMPONENTS useState hook Functions useEffect hook Return JSX from function Destructuring or props.X ES6 class, extending React.Component Class methods Lifecycle methods Return JSX from render method v0.13 ( 2015 ) v16.8 ( 2019, with hooks) 📆 Introduced in ✨ Side effects/lifecycle 💅 Returning JSX Existed since beginning, but without hooks Hooks are THE big difference
  • 247. WHY USEREDUCER? When components have a lot of state variables and state updates, spread across many event handlers all over the component 1 2 When multiple state updates need to happen at the same time (as a reaction to the same event, like “starting a game”) 3 When updating one piece of state depends on one or multiple other pieces of state 👉 STATE MANAGEMENT WITH useState IS NOT ENOUGH IN CERTAIN SITUATIONS : 👉 IN ALL THESE SITUATIONS, useReducer CAN BE OF GREAT HELP
  • 248. MANAGING STATE WITH USEREDUCER STATE WITH useReducer 👉 An alternative way of setting state, ideal for complex state and related pieces of state 👉 Stores related pieces of state in a state object 👉 useReducer needs reducer: function containing all logic to update state. Decouples state logic from component 👉 reducer: pure function (no side effects! ) that takes current state and action, and returns the next state 👉 action: object that describes how to update state 👉 dispatch: function to trigger state updates, by “sending” actions from event handlers to the reducer Like setState() with superpowers Instead of setState()
  • 249. useState HOW REDUCERS UPDATE STATE Object that contains information on how the reducer should update state action type = ‘updateDay’ payload = 23 reducer NEXT STATE CURRENT STATE RE - RENDER setState RE - RENDER useReducer 👉 Updating state in a component dispatch RETURNS NEXT ( UPDATED ) STATE UPDATE UPDATED STATE Just like array.reduce(), reducers accumulate (“reduce”) actions over time
  • 250. A MENTAL MODEL FOR REDUCERS 👉 REAL - WORLD TASK : WITHDRAWING $5,000 FROM YOUR BANK ACCOUNT YOU DO NOT GO TO YOUR BANK AND TAKE MONEY STRAIGHT FROM THE BANK’S VAULT 😂
  • 251. A MENTAL MODEL FOR REDUCERS I would like to withdraw $5,000 from account 923577 👉 REAL - WORLD TASK : WITHDRAWING $5,000 FROM YOUR BANK ACCOUNT STATE REDUCER DISPATCHER ACTION ( What needs to be updated) ( Who makes the update) ( Who requests the update) ( How to make the update)
  • 253. SECTION LECTURE THE ADVANCED USEREDUCER HOOK SECTION SUMMARY : USESTATE VS. USEREDUCER
  • 254. USESTATE VS. USEREDUCER useState useReducer 👉 Ideal for single, independent pieces of state (numbers, strings, single arrays, etc.) 👉 Logic to update state is placed directly in event handlers or effects, spread all over one or multiple components 👉 State is updated by calling setState (setter returned from useState) 👉 Imperative state updates 👉 Easy to understand and to use 👉 Ideal for multiple related pieces of state and complex state (e.g. object with many values and nested objects or arrays) 👉 Logic to update state lives in one central place, decoupled from components: the reducer 👉 State is updated by dispatching an action to a reducer 👉 Declarative state updates: complex state transitions are mapped to actions 👉 More difficult to understand and implement
  • 255. WHEN TO USE USEREDUCER? NO Do states frequently update together? Over 3 or 4 pieces of related state, including objects? Too many event handlers make components large and confusing? Are you willing to implement slightly more complex code? useState useReducer YES NO NO NO NO YES YES YES YES Just one piece of state? ☝ useState should remain your default choice for managing state
  • 257. REACT ROUTER : BUILDING SINGLE - PAGE APPLICATIONS ( SPA )
  • 258. SECTION LECTURE REACT ROUTER : BUILDING SINGLE PAGE APPLICATIONS ( SPA ) ROUTING AND SINGLE - PAGE APPLICATIONS ( SPAS )
  • 259. WHAT IS ROUTING? ROUTING 👉 With routing, we match different URLs to different UI views ( React components): routes 👉 This enables users to navigate between different applications screens, using the browser URL 👉 Keeps the UI in sync with the current browser URL 👉 Allows us to build Single-Page Applications www.example.com/login www.example.com/ www.example.com/app “Client-side routing”
  • 260. SPA RUNNING ON CLIENT 👩💻 SINGLE - PAGE APPLICATION SINGLE - PAGE APPLICATIONS ( SPA ) 👉 Application that is executed entirely on the client (browsers) 👉 Routes: different URLs correspond to different views (components) 👉 JavaScript ( React) is used to update the page ( DOM ) 👉 The page is never reloaded 👉 Feels like a native app 👉 Additional data might be loaded from a web API User clicks router link URL is changed DOM is updated: In React, react- router package does this job SERVER 🌐 DOM is updated: React component corresponding to the new URL is rendered Load data from web API
  • 262. SECTION LECTURE REACT ROUTER : BUILDING SINGLE PAGE APPLICATIONS ( SPA ) STYLING OPTIONS FOR REACT APPLICATIONS
  • 263. STYLING OPTIONS IN REACT 👉 CSS Modules One external file per component className prop CSS Component 👉 CSS-in-JS Creates new component JavaScript External file or component file Component 👉 Utility-first CSS className prop CSS JSX elements JSX element 👋 Alternative to styling with CSS : UI libraries like MUI, Chakra UI, Mantine, etc. WHERE? HOW? BASED ON SCOPE 👉 Inline CSS JSX elements style prop CSS JSX element 👉 CSS or Sass file External file className prop CSS Entire app Local Global, causes problems STYLING OPTION React doesn’t care about styling
  • 265. SECTION LECTURE REACT ROUTER : BUILDING SINGLE PAGE APPLICATIONS ( SPA ) STORING STATE IN THE URL
  • 266. THE URL FOR STATE MANAGEMENT www.example.com/app/cities/lisbon?lat=38.728&lng=-9.141 👉 The URL is an excellent place to store UI state and an alternative to useState in some situations! Examples: open/closed panels, currently selected list item, list sorting order, applied list filters 1 Easy way to store state in a global place, accessible to all components in the app Good way to “pass” data from one page into the next page 2 Makes it possible to bookmark and share the page with the exact UI state it had at the time 3 params query string path tools:
  • 267. EXAMPLE : PARAMS AND QUERY STRING www.example.com/app/cities/lisbon?lat=38.728&lng=-9.141 www.example.com/app/cities/berlin?lat=52.536&lng=13.377 👉 City name and GPS location were retrieved from the URL instead of application state!
  • 270. SECTION LECTURE ADVANCED STATE MANAGEMENT : THE CONTEXT API WHAT IS THE CONTEXT API?
  • 271. ✅ SOLUTION 2 App A C B D E F count ✅ SOLUTION 2 : CONTEXT API A SOLUTION TO PROP DRILLING 👋 Remember that a good solution to “prop drilling” is better component composition (see “Thinking in React” section) 👉 TASK : Passing state into multiple deeply nested child components ⛔ PROBLEM : “PROP DRILLING” App A C B D E F count Components that need count state 👍 READ STATE FROM EVERYWHERE 💡 SOLUTION 1 : PASSING PROPS
  • 272. WHAT IS THE CONTEXT API? CONTEXT API 👉 System to pass data throughout the app without manually passing props down the tree 👉 Allows us to “broadcast” global state to the entire app Provider: gives all child components access to value value: data that we want to make available (usually state and functions) Consumers: all components that read the provided context value 1 2 3 App A C B D E F value is updated All consumers re-render ( Consumer) ( Consumer) R E - R E N D E R R E - R E N D E R READ VALUE READ VALUE Provider value A new way of re-rendering components!
  • 274. SECTION LECTURE ADVANCED STATE MANAGEMENT : THE CONTEXT API THINKING IN REACT : ADVANCED STATE MANAGEMENT
  • 275. REVIEW : WHAT IS STATE MANAGEMENT? 🏠 State management: Giving each piece of state the right home This lecture! ✅ When to use state ✅ Types of state (accessibility): local vs. global 👉 Types of state (domain): UI vs. remote 👉 Where to place each piece of state 👉 Tools to manage all types of state From Lecture “Fundamentals of State Management”. You can keep using this 👌
  • 276. 2⃣ STATE DOMAIN TYPES OF STATE 👉 Needed only by one or few components 👉 Only accessible in component and child components 👉 Might be needed by many components 👉 Accessible to every component in the application 👉 All application data loaded from a remote server ( API ) 👉 Usually asynchronous 👉 Needs re-fetching + updating 👉 Everything else 😅 👉 Theme, list filters, form data, etc. 👉 Usually synchronous and stored in the application 🏠 LOCAL STATE 🌍 GLOBAL STATE VS. 🌐 REMOTE STATE 🪄 UI STATE VS. 1⃣ STATE ACCESSIBILITY “If this component was rendered twice, should a state update in one of them reflect in the other one?” NO
  • 277. STATE PLACEMENT OPTIONS TOOLS 👇 WHEN TO USE? 👇 🏠 Local component useState, useReducer, or useRef Local state 👪 Parent component useState, useReducer, or useRef Lifting up state 🌐 Context Context API + useState or useReducer Global state (preferably UI state) 🗃 3rd-party library Redux, React Query, SWR, Zustand, etc. Global state (remote or UI ) 📍 URL React Router Global state, passing between pages 👩💻 Browser Local storage, session storage, etc. Storing data in user’s browser 🤔 Where to place state?
  • 278. STATE MANAGEMENT TOOL OPTIONS 1⃣ STATE ACCESSIBILITY 🏠 LOCAL STATE 🌍 GLOBAL STATE 2⃣ STATE DOMAIN 🌐 REMOTE STATE 🪄 UI STATE 👉 useState 👉 useReducer 👉 useRef 👉 Context API + useState/useReducer 👉 Redux, Zustand, Recoil, etc. 👉 React Router 👉 fetch + useEffect + useState/useReducer 🤔 How to manage different types of state in practice? Tools highly specialized in handling remote state Mostly in small applications 👉 Context API + useState/useReducer 👉 Redux, Zustand, Recoil, etc. 👉 React Query 👉 SWR 👉 RTK Query
  • 281. SECTION LECTURE PERFORMANCE OPTIMIZATION AND ADVANCED USEEFFECT PERFORMANCE OPTIMIZATION AND WASTED RENDERS
  • 282. PERFORMANCE OPTIMIZATION TOOLS 1 PREVENT WASTED RENDERS 2 IMPROVE APP SPEED/ RESPONSIVENESS 3 REDUCE BUNDLE SIZE 👉 memo 👉 useMemo 👉 useCallback 👉 Passing elements as children or regular prop 👉 useMemo 👉 useCallback 👉 useTransition 👉 Using fewer 3rd-party packages 👉 Code splitting and lazy loading 👋 This list of tools and techniques is, by no means, exhaustive. You’re already doing many optimizations by following the best practices I have been showing you ✌
  • 283. WHEN DOES A COMPONENTS INSTANCE RE - RENDER? 👉 A component instance only gets re-rendered in 3 different situations: 🧠 STATE CHANGES 🌐 CONTEXT CHANGES 👪 PARENT RE - RENDERS 👉 Wasted render: a render that didn’t produce any change in the DOM 👉 Only a problem when they happen too frequently or when the component is very slow 👋 Remember: a render does not mean that the DOM actually gets updated, it just means the component function gets called. But this can be an expensive operation. Creates the false impression that changing props re-renders a component. This is NOT true. Usually no problem, as React is very fast!
  • 286. WHAT IS MEMOIZATION? 👉 Memoization: Optimization technique that executes a pure function once, and saves the result in memory. If we try to execute the function again with the same arguments as before, the previously saved result will be returned, without executing the function again. function A Call function A Store result Cache Call function A New calculated result NEW INPUTS SAME INPUTS Cached result 👉 Memoize components with memo 👉 Memoize objects with useMemo 👉 Memoize functions with useCallback 1 Prevent wasted renders 2 Improve app speed/responsiveness
  • 287. memo THE MEMO FUNCTION 👉 Used to create a component that will not re- render when its parent re-renders, as long as the props stay the same between renders 👉 Only affects props! A memoized component will still re-render when its own state changes or when a context that it’s subscribed to changes 👉 Only makes sense when the component is heavy (slow rendering), re-renders often, and does so with the same props Components re-renders ⛔ REGULAR BEHAVIOR ( NO MEMO) Child re-renders Components re-renders ✅ MEMOIZED CHILD WITH MEMO Memoized child does NOT re-render SAME PROPS Memoized child re-renders NEW PROPS Memoized component
  • 289. SECTION LECTURE PERFORMANCE OPTIMIZATION AND ADVANCED USEEFFECT UNDERSTANDING USEMEMO AND USECALLBACK
  • 290. AN ISSUE WITH MEMO In React, everything is re-created on every render (including objects and functions) In JavaScript, two objects or functions that look the same, are actually different ({} != {}) If props are different between re-renders, memo will not work If objects or functions are passed as props, the child component will always see them as new props on each re-render THEREFORE We need to memoize objects and functions, to make them stable (preserve) between re-renders (memoized {} == memoized {}) SOLUTION
  • 291. TWO NEW HOOKS : USEMEMO AND USECALLBACK useMemo AND useCallback 👉 Used to memoize values (useMemo) and functions (useCallback) between renders 👉 Values passed into useMemo and useCallback will be stored in memory (“cached”) and returned in subsequent re-renders, as long as dependencies (“inputs”) stay the same 👉 useMemo and useCallback have a dependency array (like useEffect): whenever one dependency changes, the value will be re-created Components re-renders ⛔ REGULAR BEHAVIOR ( NO USEMEMO) New value Components re-renders ✅ MEMOIZING A VALUE WITH USEMEMO Cached value is returned. NO new value SAME DEPS New value DEPS CHANGE Dependencies
  • 292. TWO NEW HOOKS : USEMEMO AND USECALLBACK useMemo AND useCallback 1 Memoizing props to prevent wasted renders (together with memo) 2 Memoizing values to avoid expensive re-calculations on every render 3 Memoizing values that are used in dependency array of another hook 👉 Used to memoize values (useMemo) and functions (useCallback) between renders 👉 Values passed into useMemo and useCallback will be stored in memory (“cached”) and returned in subsequent re-renders, as long as dependencies (“inputs”) stay the same 👉 useMemo and useCallback have a dependency array (like useEffect): whenever one dependency changes, the value will be re-created 👉 Only use them for one of the three use cases! THREE BIG USES CASES : For example to avoid infinite useEffect loops
  • 294. SECTION LECTURE PERFORMANCE OPTIMIZATION AND ADVANCED USEEFFECT OPTIMIZING BUNDLE SIZE WITH CODE SPLITTING
  • 295. THE BUNDLE AND CODE SPLITTING CLIENT 👩💻 SERVER 🌐 ON INITIAL LOAD SPA RUNS ENTIRELY ON THE CLIENT 👉 Bundle: JavaScript file containing the entire application code. Downloading the bundle will load the entire app at once, turning it into a SPA 👉 Bundle size: Amount of JavaScript users have to download to start using the app. One of the most important things to be optimized, so that the bundle takes less time to download 👉 Code splitting: Splitting bundle into multiple parts that can be downloaded over time (“lazy loading”) NO MORE FILES ARE LOADED Produced by a tool like Webpack (inside create- react-app) or Vite
  • 297. SECTION LECTURE PERFORMANCE OPTIMIZATION AND ADVANCED USEEFFECT DON'T OPTIMIZE PREMATURELY!
  • 298. DON'T OPTIMIZE PREMATURELY! ✅ Find performance bottlenecks using the Profiler and visual inspection (laggy UI ) ✅ Fix those real performance issues ✅ Memoize expensive re-renders ✅ Memoize expensive calculations ✅ Optimize context if it has many consumers and changes often ✅ Memoize context value + child components ✅ Implement code splitting + lazy loading for SPA routes DON’T! DO 🚫 Don’t optimize prematurely! 🚫 Don’t optimize anything if there is nothing to optimize... 🚫 Don’t wrap all components in memo() 🚫 Don’t wrap all values in useMemo() 🚫 Don’t wrap all functions in useCallback() 🚫 Don’t optimize context if it’s not slow and doesn’t have many consumers
  • 300. SECTION LECTURE PERFORMANCE OPTIMIZATION AND ADVANCED USEEFFECT USEEFFECT RULES AND BEST PRACTICES
  • 301. USEEFFECT DEPENDENCY ARRAY RULES ☝ Every state variable, prop, and context value used inside the effect MUST be included in the dependency array ☝ All “reactive values” must be included! That means any function or variable that reference any other reactive value ☝ Dependencies choose themselves: NEVER ignore the exhaustive-deps ESLint rule! ☝ Do NOT use objects or arrays as dependencies (objects are recreated on each render, and React sees new objects as different, {} !== {}) DEPENDENCY ARRAY RULES 👋 The same rules apply to the dependency arrays of other hooks: useMemo and useCallback Reactive value: state, prop, or context value, or any other value that references a reactive value All reactive values used in effect
  • 302. REMOVING UNNECESSARY DEPENDENCIES 👉 Move function into the effect 👉 If you need the function in multiple places, memoize it (useCallback) 👉 If the function doesn't reference any reactive values, move it out of the component 👉 Instead of including the entire object, include only the properties you need (primitive values) 👉 If that doesn’t work, use the same strategies as for functions (moving or memoizing object) 👉 If you have multiple related reactive values as dependencies, try using a reducer (useReducer) 👉 You don’t need to include setState (from useState) and dispatch (from useReducer) in the dependencies, as React guarantees them to be stable across renders 🤖 REMOVING FUNCTION DEPENDENCIES 📦 REMOVING OBJECT DEPENDENCIES 🎯 OTHER STRATEGIES
  • 303. WHEN NOT TO USE AN EFFECT ☝ Effects should be used as a last resort, when no other solution makes sense. React calls them an “escape hatch” to step outside of React THREE CASES WHERE EFFECTS ARE OVERUSED : 1 Responding to a user event. An event handler function should be used instead 2 Fetching data on component mount. This is fine in small apps, but in real-world app, a library like React Query should be used 3 Synchronizing state changes with one another (setting state based on another state variable). Try to use derived state and event handlers We actually do this in the current project, but for a good reason 😅 Avoid these as a beginner
  • 305. REDUX AND MODERN REDUX TOOLKIT ( WITH THUNKS )
  • 306. SECTION LECTURE REDUX AND MODERN REDUX TOOLKIT ( WITH THUNKS ) INTRODUCTION TO REDUX
  • 307. WHAT IS REDUX? REDUX 👉 3rd-party library to manage global state 👉 Standalone library, but easy to integrate with React apps using react-redux library 👉 All global state is stored in one globally accessible store, which is easy to update using “actions” (like useReducer) 👉 It’s conceptually similar to using the Context API + useReducer 👉 Two “versions”: ( 1 ) Classic Redux, ( 2 ) Modern Redux Toolkit ☝ You need to have a really good understanding of the useReducer hook in order to understand Redux! Global store is updated All consuming components re-render We will learn both 😎
  • 308. DO YOU NEED TO LEARN REDUX? 👋 Historically, Redux was used in most React apps for all global state. Today, that has changed, because there are many alternatives. Many apps don’t need Redux anymore, unless they need a lot of global UI state. You might not need to learn Redux… 1 Redux can be hard to learn, and this course teaches it well 😅 2 You will encounter Redux code in your job, so you should understand it 3 Some apps do require Redux (or a similar library) 🤔 WHY LEARN REDUX IN THIS COURSE?
  • 309. REDUX USE CASES 👋 Historically, Redux was used in most React apps for all global state. Today, that has changed, because there are many alternatives. Many apps don’t need Redux anymore, unless they need a lot of global UI state. Ideal use case for Redux, when there is lots of state that updates frequently For remote global state, we have better, more specialized tools THE REASON WHY MANY APPS DON’T USE REDUX
  • 310. THE MECHANISM OF THE USEREDUCER HOOK Object that contains information on how the reducer should update state CURRENT STATE dispatch NEXT STATE reducer RE - RENDER EVENT HANDLER IN COMPONENT action type = ‘deposit’ payload = 50
  • 311. THE MECHANISM OF REDUX STORE NEXT STATE CURRENT STATE RE - RENDER reducer reducer reducer ... dispatch All global state lives in this centralized container. It’s the single source of truth of global state in the app Each reducer is a pure function that calculates the next state (state transition) based on the action and the current state. Usually one reducer per app feature (e.g. shopping cart + user data + theme) action type = ‘deposit’ payload = 50 EVENT HANDLER IN COMPONENT
  • 312. THE MECHANISM OF REDUX STORE CURRENT STATE dispatch Action creator function reducer reducer reducer ... action type = ‘deposit’ payload = 50 NEXT STATE To automate writing action. Helpful to keep all possible actions in one central place. ( This is a convention, not a must) RE - RENDER EVENT HANDLER IN COMPONENT 👉 Redux cycle 👉 Goal: make the state update logic separate from the rest of the application
  • 313. THE MECHANISM OF REDUX STORE NEXT STATE CURRENT STATE dispatch Action creator function reducer reducer reducer ... I would like to deposit $50 from my account action type = ‘deposit’ payload = 50 👉 REAL - WORLD TASK : DEPOSITING $50 INTO YOUR BANK ACCOUNT RE - RENDER EVENT HANDLER IN COMPONENT
  • 315. SECTION LECTURE REDUX AND MODERN REDUX TOOLKIT ( WITH THUNKS ) REDUX MIDDLEWARE AND THUNKS
  • 316. WHAT IS REDUX MIDDLEWARE? STORE dispatch MIDDLEWARE 🤔 Where to make an asynchronous API call (or any other async operation) in Redux? 🚫 No asynchronous operations 🚫 Reducers need to be pure functions COMPONENT 🤷 Can make asynchronous operations and then dispatch 🤷 Fetching data in components is not ideal 👍 Perfect for asynchronous code 👍 API calls, timers, logging, etc. 👍 The place for side effects A function that sits between dispatching the action and the store. Allows us to run code after dispatching, but before reaching the reducer in the store.
  • 317. REDUX THUNKS STORE dispatch THUNK MIDDLEWARE 🚫 No asynchronous operations 🚫 Reducers need to be pure functions COMPONENT 🤷 Can make asynchronous operations and then dispatch 🤷 Fetching data in components is not ideal 👍 Perfect for asynchronous code 👍 API calls, timers, logging, etc. 👍 The place for side effects action type = ‘deposit’ payload = 50 action type = ‘deposit’ payload = {data} 🤔 Where to make an asynchronous API call (or any other async operation) in Redux?
  • 319. SECTION LECTURE REDUX AND MODERN REDUX TOOLKIT ( WITH THUNKS ) WHAT IS REDUX TOOLKIT ( RTK ) ?
  • 320. WHAT IS REDUX TOOLKIT? REDUX TOOLKIT 👉 The modern and preferred way of writing Redux code 👉 An opinionated approach, forcing us to use Redux best practices 👉 100% compatible with “classic” Redux, allowing us to use them together 👉 Allows us to write a lot less code to achieve the same result (less “boilerplate”) 👉 Gives us 3 big things (but there are many more…): We can write code that “mutates” state inside reducers (will be converted to immutable logic behind the scenes by “Immer” library) Action creators are automatically created Automatic setup of thunk middleware and DevTools 1 2 3
  • 322. SECTION LECTURE REDUX AND MODERN REDUX TOOLKIT ( WITH THUNKS ) REDUX VS. CONTEXT API
  • 323. CONTEXT API VS. REDUX CONTEXT API + useReducer REDUX 👍 Built into React 👍 Easy to set up a single context 👎 Additional state “slide” requires new context set up from scratch (“provider hell” in App.js) 👎 No mechanism for async operations 👎 Performance optimization is a pain 👎 Only React DevTools 👎 Requires additional package (larger bundle size) 👎 More work to set up initially 👍 Once set up, it’s easy to create additional state “slices” 👍 Supports middleware for async operations 👍 Performance is optimized out of the box 👍 Excellent DevTools Keep in mind that we should not use these solutions for remote state
  • 324. WHEN TO USE CONTEXT API OR REDUX? CONTEXT API + useReducer REDUX 👉 When you just need to share a value that doesn’t change often [ Color theme, preferred language, authenticated user, …] 👉 When you need to solve a simple prop drilling problem 👉 When you need to manage state in a local sub-tree of the app 👉 When you have lots of global UI state that needs to be updated frequently (because Redux is optimized for this) [Shopping cart, current tabs, complex filters or search, …] 👉 When you have complex state with nested objects and arrays (because you can mutate state with Redux Toolkit) “Use the Context API for global state management in small apps” “Use Redux for global state management in large apps” 👋 There is no right answer that fits every project. It all depends on the project needs! For example in the compound component pattern These are not super common in UI state
  • 327. REACT ROUTER WITH DATA LOADING ( V6.4 + )
  • 328. SECTION LECTURE REACT ROUTER WITH DATA LOADING ( V6.4 + ) APPLICATION PLANNING
  • 329. THE PROJECT : 🍕 FAST REACT PIZZA CO. REMEMBER OUR VERY FIRST PROJECT? 👉 Now the same restaurant (business) needs a simple way of allowing customers to order pizzas and get them delivered to their home 👉 We were hired to build the application front-end 🎉
  • 330. Break the desired UI into components 1 2 Build a static version (no state yet) 3 Think about state management + data flow 🎯 HOW TO PLAN AND BUILD A REACT APPLICATION FROM THE EARLIER “THINKING IN REACT” LECTURE : 👉 This works well for small apps with one page and a few features 👉 In real-world apps, we need to adapt this process
  • 331. 1 Gather application requirements and features 3 Divide the application into feature categories 2 Divide the application into pages 👉 Think about the overall and page-level UI 👉 Break the desired UI into components 👉 Design and build a static version (no state yet) 👉 Think about state management + data flow 4 Decide on what libraries to use (technology decisions) 🎯 HOW TO PLAN AND BUILD A REACT APPLICATION This is just a rough overview. In the real-world, things are never this linear From earlier From earlier From earlier
  • 332. 👨💼 PROJECT REQUIREMENTS FROM THE BUSINESS 👉 Very simple application, where users can order one or more pizzas from a menu 👉 Requires no user accounts and no login: users just input their names before using the app 👉 The pizza menu can change, so it should be loaded from an API 👉 Users can add multiple pizzas to a cart before ordering 👉 Ordering requires just the user’s name, phone number, and address 👉 If possible, GPS location should also be provided, to make delivery easier 👉 User’s can mark their order as “priority” for an additional 20% of the cart price 👉 Orders are made by sending a POST request with the order data (user data + selected pizzas) to the API 👉 Payments are made on delivery, so no payment processing is necessary in the app 👉 Each order will get a unique ID that should be displayed, so the user can later look up their order based on the ID 👉 Users should be able to mark their order as “priority” order even after it has been placed From these requirements, we can understand the features we need to implement STEP 1 ✅ DONE
  • 333. FEATURES + PAGES All features can be placed into one of these. So this is what the app will essentially be about 1⃣ User 2⃣ Menu 3⃣ Cart 4⃣ Order 1⃣ Homepage 2⃣ Pizza menu 3⃣ Cart 4⃣ Placing a new order 5⃣ Looking up an order /order/:orderID /cart / /menu /order/new FEATURE CATEGORIES NECESSARY PAGES STEP 2 + 3
  • 334. STATE MANAGEMENT + TECHNOLOGY DECISIONS 1⃣ User 2⃣ Menu 3⃣ Cart 4⃣ Order STEP 3 + 4 STATE “DOMAINS” / “SLICES” TYPES OF STATE Global UI state (no accounts, so stays in app) Global remote state (menu is fetched from API ) Global UI state (no need for API, just stored in app) Global remote state (fetched and submitted to API ) These usually map quite nicely to the app features 👉 Routing The standard for React SPAs Trendy way of styling applications that we want to learn 👉 Styling New way of fetching data right inside React Router (v6.4 + ) that is worth exploring (“render-as-you-fetch” instead of “fetch-on- render”). Not really state management, as it doesn't persist state. 👉 Remote state management State is fairly complex. Redux has many advantages for UI state. Also, we want to practice Redux a bit more 👉 UI State management This is just one of many tech stacks we could have chosen
  • 337. SECTION LECTURE TAILWIND CSS CRASH COURSE : STYLING THE APP WHAT IS TAILWIND CSS?
  • 338. WHAT IS TAILWIND CSS? 👉 “A utility-first CSS framework packed with utility classes like flex, text-center and rotate-90 that can be composed to build any design, directly in your markup ( HTML or JSX ) ” 👉 Utility-first CSS approach: writing tiny classes with one single purpose, and then combining them to build entire layouts 👉 In tailwind, these classes are already written for us. So we’re not gonna write any new CSS, but instead use some of tailwind’s hundreds of classes TAILWIND CSS
  • 339. THE BAD THE GOOD THE GOOD AND BAD ABOUT TAILWIND 👍 You don’t need to think about class names 👍 No jumping between files to write markup and styles 👍 Immediately understand styling in any project that uses tailwind 👍 Tailwind is a design system: many design decisions have been taken for you, which makes UIs look better and more consistent 👍 Saves a lot of time, e.g. on responsive design 👍 Docs and VS Code integration are great 👎 Markup ( HTML or JSX ) looks very unreadable, with lots of class names (you get used to it) 👎 You have to learn a lot of class names (but after a day of usage you know fundamentals) 👎 You need to install and set up tailwind on each new project 👎 You’re giving up on “vanilla CSS” 😢 👋 Many people love to hate on tailwind for no reason. Please don’t be that person! Try it before judging 🙏 These two are enough to give tailwind a try!
  • 341. SETTING UP OUR BIGGEST PROJECT + STYLED COMPONENTS
  • 342. SECTION LECTURE SETTING UP OUR BIGGEST PROJECT + STYLED COMPONENTS APPLICATION PLANNING
  • 343. THE PROJECT : THE WILD OASIS 👉 “The Wild Oasis” is a small boutique hotel with 8 luxurious wooden cabins 👉 They need a custom-built application to manage everything about the hotel: bookings, cabins and guests 👉 This is the internal application used inside the hotel to check in guests as they arrive 👉 They have nothing right now, so they also need the API 👉 Later they will probably want a customer-facing website as well, where customers will be able to book stays, using the same API INTERNAL HOTEL MANAGEMENT APP API CUSTOMER - FACING WEBSITE TO BOOK STAYS Later
  • 344. 1 Gather application requirements and features 3 Divide the application into feature categories 2 Divide the application into pages 4 Decide on what libraries to use (technology decisions) REVIEW : HOW TO PLAN A REACT APPLICATION
  • 345. 👨💼 PROJECT REQUIREMENTS FROM THE BUSINESS 👉 Users of the app are hotel employees. They need to be logged into the application to perform tasks 👉 New users can only be signed up inside the applications (to guarantee that only actual hotel employees can get accounts) 👉 Users should be able to upload an avatar, and change their name and password 👉 App needs a table view with all cabins, showing the cabin photo, name, capacity, price, and current discount 👉 Users should be able to update or delete a cabin, and to create new cabins (including uploading a photo) 👉 App needs a table view with all bookings, showing arrival and departure dates, status, and paid amount, as well as cabin and guest data 👉 The booking status can be “unconfirmed” (booked but not yet checked in), “checked in”, or “checked out”. The table should be filterable by this important status 👉 Other booking data includes: number of guests, number of nights, guest observations, whether they booked breakfast, breakfast price 👉 Users should be able to delete, check in, or check out a booking as the guest arrives (no editing necessary for now) 👉 Bookings may not have been paid yet on guest arrival. Therefore, on check in, users need to accept payment (outside the app), and then confirm that payment has been received (inside the app) 👉 On check in, the guest should have the ability to add breakfast for the entire stay, if they hadn’t already 👉 Guest data should contain: full name, email, national ID, nationality, and a country flag for easy identification 👉 The initial app screen should be a dashboard, to display important information for the last 7, 30, or 90 days: 👉 A list of guests checking in and out on the current day. Users should be able to perform these tasks from here 👉 Statistics on recent bookings, sales, check ins, and occupancy rate 👉 A chart showing all daily hotel sales, showing both “total” sales and “extras” sales (only breakfast at the moment) 👉 A chart showing statistics on stay durations, as this is an important metric for the hotel 👉 Users should be able to define a few application-wide settings: breakfast price, min and max nights/booking, max guests/booking 👉 App needs a dark mode STEP 1
  • 346. 👨💼 PROJECT REQUIREMENTS FROM THE BUSINESS 👉 Users of the app are hotel employees. They need to be logged into the application to perform tasks 👉 New users can only be signed up inside the applications (to guarantee that only actual hotel employees can get accounts) 👉 Users should be able to upload an avatar, and change their name and password 👉 App needs a table view with all cabins, showing the cabin photo, name, capacity, price, and current discount 👉 Users should be able to update or delete a cabin, and to create new cabins (including uploading a photo) 👉 App needs a table view with all bookings, showing arrival and departure dates, status, and paid amount, as well as cabin and guest data 👉 The booking status can be “unconfirmed” (booked but not yet checked in), “checked in”, or “checked out”. The table should be filterable by this important status 👉 Other booking data includes: number of guests, number of nights, guest observations, whether they booked breakfast, breakfast price 👉 Users should be able to delete, check in, or check out a booking as the guest arrives (no editing necessary for now) 👉 Bookings may not have been paid yet on guest arrival. Therefore, on check in, users need to accept payment (outside the app), and then confirm that payment has been received (inside the app) 👉 On check in, the guest should have the ability to add breakfast for the entire stay, if they hadn’t already 👉 Guest data should contain: full name, email, national ID, nationality, and a country flag for easy identification 👉 The initial app screen should be a dashboard, to display important information for the last 7, 30, or 90 days: 👉 A list of guests checking in and out on the current day. Users should be able to perform these tasks from here 👉 Statistics on recent bookings, sales, check ins, and occupancy rate 👉 A chart showing all daily hotel sales, showing both “total” sales and “extras” sales (only breakfast at the moment) 👉 A chart showing statistics on stay durations, as this is an important metric for the hotel 👉 Users should be able to define a few application-wide settings: breakfast price, min and max nights/booking, max guests/booking 👉 App needs a dark mode STEP 1 SETTINGS DASHBOARD AUTHENTICATION GUESTS CHECK IN / OUT BOOKINGS CABINS
  • 347. FEATURES + PAGES STEP 2 + 3 1⃣ Bookings 2⃣ Cabins 3⃣ Guests 4⃣ Dashboard 5⃣ Check in and out 6⃣ App settings 7⃣ Authentication 1⃣ Dashboard 2⃣ Bookings 3⃣ Cabins 4⃣ Booking check in 5⃣ App settings 6⃣ User sign up 7⃣ Login 8⃣ Account settings /login /dashboard /checkin/:bookingID FEATURE CATEGORIES NECESSARY PAGES /account /users /settings /cabins /bookings 👋 We will discuss state later. Most of it will be global
  • 348. CSR WITH PLAIN REACT SSR WITH FRAMEWORK CLIENT - SIDE RENDERING ( CSR ) OR SERVER - SIDE RENDERING ( SSR ) ? STEP 4 👉 Used to build Single-Page Applications ( SPAs) 👉 All HTML is rendered on the client 👉 All JavaScript needs to be downloaded before apps start running: bad for performance 👉 One perfect use case: apps that are used “internally” as tools inside companies, that are entirely hidden behind a login 👉 Used to build Multi-Page Applications ( MPAs) 👉 Some HTML is rendered in the server 👉 More performant, as less JavaScript needs to be downloaded 👉 The React team is moving more and more in this direction This is exactly what we want to build in this project
  • 349. TECHNOLOGY DECISIONS 👉 Routing The standard for React SPAs STEP 4 Very popular way of writing component-scoped CSS, right inside JavaScript. A technology worth learning 👉 Styling There is almost no UI state needed in this app, so one simple context with useState will be enough. No need for Redux 👉 UI State management Context API The best way of managing remote state, with features like caching, automatic re-fetching, pre-fetching, offline support, etc. Alternatives are SWR and RTK Query, but this is the most popular 👉 Remote state management 👉 Form management Handling bigger forms can be a lot of work, such as manual state creation and error handling. A library can simplify all this 👉 Other tools React icons / React hot toast / Recharts / date-fns / Supabase
  • 352. SECTION LECTURE SUPABASE CRASH COURSE : BUILDING A BACK - END! WHAT IS SUPABASE?
  • 353. WHAT IS SUPABASE? 🌐 BACK - END 👉 Service that allows developers to easily create a back-end with a Postgres database 👉 Automatically creates a database and API so we can easily request and receive data from the server 👉 No back-end development needed 🥳 👉 Perfect to get up and running quickly! 👉 Not just an API : Supabase also comes with easy- to-use user authentication and file storage WITH SUPABASE, WE DON’T NEED TO DO ANY OF THIS MANUALLY! IT’S ALL INCLUDED SUPABASE
  • 355. SECTION LECTURE SUPABASE CRASH COURSE : BUILDING A BACK - END! MODELING APPLICATION STATE
  • 356. MODELING STATE 1⃣ Bookings 2⃣ Cabins 3⃣ Guests 4⃣ Dashboard 5⃣ Check in and out 6⃣ App settings 7⃣ Authentication FEATURE CATEGORIES STATE “DOMAINS” / “SLICES” 1⃣ Bookings 2⃣ Cabins 3⃣ Guests 4⃣ Settings 5⃣ Users 👉 All this state will be global remote state, stored within Supabase 👉 There will be one table for each state “slice” in the database
  • 357. THE BOOKINGS TABLE 👉 Bookings are about a guest renting a cabin 👉 So a booking needs information about what guest is booking which cabin: we need to connect them 👉 Supabase uses a Postgres DB, which is SQL (relational DB ) . So we join tables using foreign keys BOOKING GUEST CABIN id guestId cabinId ... id id name ... email ... We connect a booking with a cabin by storing the cabin’s id (primary key) inside the booking cabinId (foreign key)
  • 361. API CACHE WHAT IS REACT QUERY? API 👉 Powerful library for managing remote (server) state 👉 Many features that allow us to write a lot less code, while also making the UX a lot better: 👉 Data is stored in a cache 👉 Automatic loading and error states 👉 Automatic re-fetching to keep state synched 👉 Pre-fetching 👉 Easy remote state mutation (updating) 👉 Offline support 👉 Needed because remote state is fundamentally different from regular ( UI ) state REACT QUERY “cabins” fetch(“api.com /cabins”) COMPONENT A fetch(“api.com /cabins”) COMPONENT B “cabins” “cabins” NO ADDITIONAL API REQUEST
  • 364. SECTION LECTURE ADVANCED REACT PATTERNS AN OVERVIEW OF REUSABILITY IN REACT
  • 365. HOW TO REUSE CODE IN REACT? Custom hooks 👉 I need to reuse: Use props as a component API, to enable custom behavior. Can be stateless, stateful, or structural components Components and props children prop Render props pattern Compound component pattern UI STATEFUL LOGIC Logic with hooks For complete control over what the component renders, by passing in a function that tells the component what to render. Was more common before hooks, but still useful To customize the component’s content For very self-contained components that need/want to manage their own state. Compound components are like fancy super-components 👋 There are even more patterns, but these ones matter most
  • 368. OVERVIEW OF NEXT.JS WITH THE "APP" ROUTER
  • 369. SECTION LECTURE OVERVIEW OF NEXT.JS WITH THE "APP" ROUTER AN OVERVIEW OF SERVER - SIDE RENDERING ( SSR )
  • 370. REVIEW : THE RISE OF SINGLE - PAGE APPLICATIONS 👩💻 CLIENT / FRONT - END 🌐 SERVER / BACK - END BROWSER RENDER WEBPAGE SERVER - SIDE RENDERING CLIENT - SIDE RENDERING BROWSER RENDER WEBPAGE API 1 THE “OLD” WAY 2 THE “MODERN” WAY 3 GETTING MODERN AGAIN
  • 371. CLIENT - SIDE RENDERING SERVER - SIDE RENDERING CLIENT - SIDE RENDERING ( CSR ) VS. SERVER - SIDE RENDERING ( SSR ) 👉 HTML is rendered on the client (the user’s computer) using JavaScript 👎 Slower initial page loads: 👉 Bigger JavaScript bundle needs to be downloaded before app starts running 👉 Data is fetched after components mount 👍 Highly interactive: All the code and content has already been loaded (except data) 👎 SEO can be problematic 👉 HTML is rendered on the server (the developer’s computer) 👍 Faster initial page loads: 👉 Less JavaScript needs to be downloaded and executed 👉 Data is fetched before HTML is rendered 👎 Less interactive: Pages might be downloaded on demand and require full page reloads 👍 SEO-friendly: Content is easier for search engines to index
  • 372. CLIENT - SIDE RENDERING SERVER - SIDE RENDERING WHEN TO USE CSR AND SSR? 👉 SPAs: Perfect for building highly interactive web apps 👉 Apps that don’t need SEO : 👉 Apps that are used “internally” as tools inside companies 👉 Apps that are entirely hidden behind a login 👉 Content-driven websites or apps where SEO is essential: E-commerce, blogs, news, marketing websites, etc. This is what we’ve been doing so far TWO TYPES OF SSR : 1 Static: HTML generated at build time (often called Static Site Generation, or SSG ) 2 Dynamic: HTML generated each time server receives new request (some call only this SSR ) More on this later
  • 373. SSR TYPICAL TIMELINE OF CSR VS. SSR WITH DATA FETCHING CSR SERVER 🌐 CLIENT 👩💻 Fetch data SERVER 🌐 CLIENT 👩💻 Empty page Render app with data Fetch data Render app with data Hydrate First paint ( FCP ) Content paint ( LCP ) Render spinner Content paint ( LCP ) First paint ( FCP ) Moved to the server Download JS bundle Download JS bundle ⚡ Much faster!
  • 375. SECTION LECTURE OVERVIEW OF NEXT.JS WITH THE "APP" ROUTER THE MISSING PIECE : HYDRATION
  • 376. HYDRATION WHAT IS HYDRATION? SERVER 🌐 CLIENT 👩💻 React component tree SSRd HTML React app The React bundle is sent as well Content paint ( LCP ) Page interactive 👉 Adds back the interactivity and event handlers that were lost when HTML was server-side rendered 👉 Watering the “dry” HTML with the “water” of interactivity and event handlers 👉 React builds the component tree on the client and compares it with the actual SSRd DOM : They must be the same so React can adopt it! 👉 Common hydration error causes: incorrect HTML element nesting, different data used for rendering, using browser-only APIs, side effects, etc. Rendered webpage DOM Hydration
  • 378. SECTION LECTURE OVERVIEW OF NEXT.JS WITH THE "APP" ROUTER WHAT IS NEXT.JS?
  • 379. WHAT IS NEXT.JS? 👉 Meta-framework built on top of React: we still use components, props, react hooks, etc. 👉 Opinionated way of building React apps: Set of conventions and best practices regarding routing, data fetching, etc. 👉 Allows us to build complex full-stack web apps and sites 👉 Allows us to use cutting-edge React features that need to be integrated into a framework: Suspense, Server Components, Server Actions, steaming, etc. NEXT.JS “THE REACT FRAMEWORK FOR THE WEB” React’s full-stack architecture vision
  • 380. THE NEXT.JS KEY INGREDIENTS SERVER - SIDE RENDERING ( DYNAMIC AND STATIC ) FILE - BASED ROUTING CONVENTIONS DATA FETCHING AND MUTATION ON THE SERVER OPTIMIZATIONS 👉 Dynamic or static can be selected for each route 👉 Folders as routes 👉 Special files for pages, layouts, loaders, etc. 👉 Fetching data directly in Server Components 👉 Mutations in Server Actions 👉 Images 👉 Fonts 👉 SEO 👉 Preloading
  • 381. TWO FLAVOURS OF NEXT.JS : "APP" AND "PAGES" ROUTER LEGACY NEXT.JS : “PAGES” ROUTER MODERN NEXT.JS : “APP” ROUTER 👉 The first Next.js router since v1 ( 2016 ) 👉 Still supported and updated in the future 👍 Overall more simple and easy to learn 👎 Simple things like layouts are confusing to implement 👎 Data fetching using Next.js-specific APIs such as getStaticProps and getServerSideProps 👉 Introduced in Next.js 13.4 ( 2023 ) 👉 Recommend for new projects 👉 Implements React’s full-stack architecture: Server Components, Server Actions, Streaming, etc. 👍 Easy fetching with fetch() right in components 👍 Extremely easy to create layouts, loaders, etc. 👍 More advanced routing (parallel routing, etc.) 👍 Better DX ( Developer Experience) and UX 👎 Caching is very aggressive and confusing 👎 Steep learning curve (but it’s React) 👋 We’re gonna learn the “app” router from the start. At the end, there is a section on the fundamentals of the “pages” router
  • 383. SECTION LECTURE OVERVIEW OF NEXT.JS WITH THE "APP" ROUTER WHAT ARE REACT SERVER COMPONENTS?
  • 384. WHY REACT SERVER COMPONENTS? 👍 Interactive 👍 Components 👎 Requires lots of JS 👎 Client-server data waterfalls 100% Server-side 100% Client-Side UI = f(state) UI = f(data) UI = f(data, state) We “hack” this by storing fetched data in state too 🤔 What if we could take the best of both worlds? 🧩 The answer is a completely new React paradigm: React Server Components ( RSC ) 👎 NO components 👍 Easy and fast to fetch all data 👍 Close to the data source 👍 Needs to ship 0 kb of JS Closer to what a real-world app is RSC
  • 385. WHAT ARE REACT SERVER COMPONENTS? REACT SERVER COMPONENTS ( RSC ) 👉 A new full-stack architecture for React apps 👉 Introduces the server as an integral part of React component trees: server components 👉 We write frontend code next to backend code in a natural way that “feels” like regular React ☝ RSC is NOT active by default in new React apps (e.g. Vite apps): it needs to be implemented by a framework like Next.js (“app router”) 2 SERVER COMPONENTS 1 CLIENT COMPONENTS 👉 “Regular” components 👉 Created with “use client” directive at the top of the module 👉 Components that are only rendered on the server 👉 Don’t make it into the bundle ( 0 kb) 👉 We can build the back-end with React! 👉 Default in apps that use the RSC architecture (like Next.js) UI = f(state) UI = f(data) Name of the new PARADIGM Name of the new COMPONENT TYPE
  • 386. Client sub-tree. Child modules need no “use client” AN EXAMPLE + THE SERVER - CLIENT BOUNDARY ( Simplified tree) CabinRow App Menu Delete Sidebar Duplicate Header Main “use client” DarkMode SortBy Avatar Table “use client” “use client” Also a sub-tree, but a small one Server component Client component Edit Split point between server and client code Server-client boundary
  • 387. SERVER COMPONENTS VS. CLIENT COMPONENTS 🔼 Lifting state up ✅ YES ❌ N.A. 🔽 Props ✅ YES ✅ YES ( Must be serializable when passed to client components. No functions or classes) 📥 Data fetching 🤷 Also possible, preferably with library ✅ Preferred. Use async/away in component 📦 Can import Only client components (can’t go back in the client-server boundary) Client and server components ✍ Can render Client components and server components passed as props Client and server components 🔄 When re-render? On state change On URL change (navigation) CLIENT COMPONENTS SERVER COMPONENTS ⚡ State/hooks ✅ YES ❌ NO “use client” Default
  • 388. REACT WITH RSC A SIMPLE NEW MENTAL MODEL 👩💻 CLIENT 🌐 SERVER Components “TRADITIONAL” REACT View Server Components Interaction UPDATE STATE RE - RENDER DISPLAY FETCH DATA PROPS FETCH DATA UPDATE URL RE - RENDER View Client Components DISPLAY Interaction UPDATE STATE RE - RENDER Navigation
  • 389. THE GOOD AND BAD OF THE RSC ARCHITECTURE THE BAD THE GOOD 👍 We can compose entire full-stack apps with React components alone (+ server actions 👉) 👍 One single codebase for front and back-end 👍 Server components have more direct and secure access to the data source (no API, no exposing API keys, etc.) 👍 Eliminate client-server waterfalls by fetching all the data needed for a page at once before sending it to the client (not each component) 👍 “Disappearing code”: server components ship no JS, so they can import huge libraries “for free” 👎 Makes React more complex 👎 More things to learn and understand 👎 Things like Context API don’t work in server components 👎 More decisions to make: “Should this be a client or a server component?”, “Should I fetch this data on the server or the client?”, etc. 👎 Sometimes you still need to build an API (for example if you also have a mobile app) 👎 Can only be used within a framework
  • 391. SECTION LECTURE OVERVIEW OF NEXT.JS WITH THE "APP" ROUTER HOW RSC WORKS BEHIND THE SCENES
  • 392. A QUICK REVIEW OF RENDERING IN REACT Components Tree of component instances ( Component tree) React element tree (“Virtual DOM”) RENDER DOM Elements ( HTML ) COMMIT TO DOM “TRADITIONAL” REACT B B A C B A A B C B B A C B D 🤔 How does this work in RSC? 👉
  • 393. HOW RSC WORKS BEHIND THE SCENES COMPLETE “VIRTUAL DOM” C C C React Element React Element React Element React Element React Element React Element S C S C C S COMPONENT TREE RENDER SCs SERVER CLIENT “VIRTUAL DOM” OF SC + TREES OF CC (RSC PAYLOAD ) “HOLE” WHERE THE CC WILL BE RENDERED Server component ( SC ) render render render The code from the SC has disappeared Client component ( CC ) RENDER CCs SEND TO CLIENT NOT server and client in the typical sense… Powered by the framework’s bundler render render render “use client” “use client” C React Element C C React Element React Element React Element React Element React Element 🔽 Serialized props passed from SC to CC 📄 URL to script with component code
  • 394. HOW RSC WORKS BEHIND THE SCENES S C C C S “use client” “use client” COMPLETE “VIRTUAL DOM” C C C React Element React Element RENDER SCs React Element React Element React Element React Element React Element COMPONENT TREE SERVER CLIENT “VIRTUAL DOM” OF SC + TREES OF CC (RSC PAYLOAD ) “HOLE” WHERE THE CC WILL BE RENDERED 🔽 Serialized props passed from SC to CC 📄 URL to script with component code The code from the SC has disappeared 👉 Describes the UI as data, not as finished HTML 👉 When a SC is re-rendered: React is able to merge (“reconcile”) the current tree on the client with a new tree coming from the server 👉 As a result, UI state can be preserved when a SC re-renders, instead of completely re-generating the page as HTML 🤔 Why RSC Payload? Why not render SCs as HTML? RENDER CCs SEND TO CLIENT NOT server and client in the typical sense… Powered by the framework’s bundler S re-render React Element Merge into existing tree React Element
  • 395. A SIMPLIFIED REVIEW REACT WITH RSC “TRADITIONAL” REACT Component tree “Virtual DOM” RENDER DOM Elements COMMIT Complete “Virtual DOM” DOM Elements Component tree of SC and CC “Virtual DOM” of SC + Component trees of CC COMMIT RENDER SC RENDER CC 👉 “Hole” where CC will render 👉 Serialized props from SC 👉 URL to script with code FOR EACH CC IN TREE : RSC PAYLOAD – SEND “RSC PAYLOAD” TO CLIENT CLIENT 1 2 UI = f(data)(state) UI = f(data, state) 1 2 ☝ Steps don’t wait for one another. Completed render work is streamed to client SERVER
  • 397. SECTION LECTURE OVERVIEW OF NEXT.JS WITH THE "APP" ROUTER RSC VS. SSR : HOW ARE THEY RELATED?
  • 398. REVIEW : SERVER - SIDE RENDERING ( SSR ) SERVER 🌐 CLIENT 👩💻 👉 SSR : “Just take this component tree, render it as HTML, and send that HTML to the browser” Hydrate Component tree Interactive React App HTML RENDER 👉 “Also send the React code to make the HTML interactive” 👋 We’ll be talking about dynamic SSR ( HTML generated at runtime)
  • 399. RSC VS. SSR 🤔 What about RSC? THE RELATIONSHIP BETWEEN RSC AND SSR Complete “Virtual DOM” DOM Elements Component tree of SC and CC “Virtual DOM” of SC + Component trees of CC RENDER SC RENDER CC SEND “RSC PAYLOAD” CLIENT SERVER SERVER 🌐 CLIENT 👩💻 👉 SSR : “Just take this component tree, render it as HTML, and send that HTML to the browser” Hydrate Interactive React App 👉 RSC is NOT the same as SSR : they are separate technologies 👉 RSC does NOT replace SSR 👉 They usually work together: frameworks can combine them 👉 Both client and server components are initially rendered on the server when SSR is used 👉 In the RSC model, “server” just means “the developer’s computer” 👉 Result: RSC does NOT require a running web server! Components could run only once at built time (static site generation) Also works like this when coupled with RSC. ALL components are pre-rendered on the server Doesn’t need to be an actual web server. Simply “another computer” HTML 👉 “Also send the React code to make the HTML interactive” Doesn’t need to be a browser
  • 400. RSC VS. SSR THE RELATIONSHIP BETWEEN RSC AND SSR SERVER 🌐 CLIENT 👩💻 👉 SSR : “Just take this component tree, render it as HTML, and send that HTML to the browser” Hydrate Interactive React App 👉 RSC is NOT the same as SSR : they are separate technologies 👉 RSC does NOT replace SSR 👉 They usually work together: frameworks can combine them 👉 Both client and server components are initially rendered on the server when SSR is used 👉 In the RSC model, “server” just means “the developer’s computer” 👉 Result: RSC does NOT require a running web server! Components could run only once at built time (static site generation) Component tree ( SC and CC ) HTML RENDER RSC PAYLOAD 👉 “Also send the React code to make the HTML interactive” Hydrate CCs Only client components So that React has the entire component tree on the client, not just HTML. Necessary to preserve UI state on future SC re-renders 👋 SSR happens only on initial render. On re-renders, client components only render on the actual client
  • 402. STARTING TO BUILD THE "WILD OASIS" WEBSITE
  • 403. SECTION LECTURE STARTING TO BUILD THE "WILD OASIS" WEBSITE PROJECT PLANNING : "THE WILD OASIS" CUSTOMER WEBSITE
  • 404. THE PROJECT : THE WILD OASIS WEBSITE 👉 Remember: “The Wild Oasis” is a small boutique hotel with 8 luxurious wooden cabins ✅ We built their application to manage everything about the hotel: bookings, cabins and guests ✅ We also build the API using Supabase 👉 Now they need a customer-facing website where guests can learn about the hotel, browse all cabins, reserve a cabin, and create and update their profile 👉 Updating data in the internal app should update the website, so we use the same DB and API 👉 We are hired again 😎 🎉 INTERNAL HOTEL MANAGEMENT APP API CUSTOMER - FACING WEBSITE TO BOOK STAYS NOW ✅ ✅
  • 405. 👨💼 PROJECT REQUIREMENTS FROM THE BUSINESS PROFILE ABOUT AUTHENTICATION RESERVATIONS CABINS 👉 Users of the app are potential guests and actual guests 👉 Guests should be able to learn all about the Wild Oasis Hotel 👉 Guests should be able to get information about each cabin and see booked dates 👉 Guests should be able to filter cabins by their maximum guest capacity 👉 Guests should be able to reserve a cabin for a certain date range 👉 Reservations are not paid online. Payments will be made at the property upon arrival. Therefore, new reservations should be set to “unconfirmed” (booked but not yet checked in) 👉 Guests should be able to view all their past and future reservations 👉 Guests should be able to update or delete a reservation 👉 Guests need to sign up and log in before they can reserve a cabin and perform any operation 👉 On sign up, each guest should get a profile in the DB 👉 Guests should be able to set and update basic data about their profile to make check-in at the hotel faster
  • 406. FEATURES + PAGES 1⃣ About 2⃣ Cabins 3⃣ Reservations 4⃣ Authentication 5⃣ Profile 1⃣ Homepage 2⃣ About page 3⃣ Cabin overview 4⃣ Cabin detail 5⃣ Login 6⃣ Reservation list 7⃣ Edit reservation 8⃣ Update profile /account/reservations/edit / /cabins/:cabinId FEATURE CATEGORIES NECESSARY PAGES /account/profile /account/reservations /login /cabins/ /about
  • 407. TECHNOLOGY DECISIONS We might still need global UI state in a Next.js app. For that, we can use the Context API, Redux, or any of the other solutions. In this case the Context API will be enough. 👉 UI State management Context API Modern way of writing CSS. Extremely easy to integrate into Next.js. Most styles and markup will be pre-written anyway in this project. 👉 Styling 👉 Framework The most popular React meta-framework. Handles routing, SSR, data fetching and even remote state management (in a way…), therefore replacing many tools we had to include before We’ll use the data and API we already built in the first “Wild Oasis” project. If you skipped that project, please go back to the “Supabase” section to set everything up 👉 DB / API
  • 410. SECTION LECTURE DATA FETCHING, CACHING, AND RENDERING WHAT IS REACT SUSPENSE?
  • 411. Products Filter List WHAT IS REACT SUSPENSE? SUSPENSE 👉 Built-in React component that we can use to catch/isolate components (or entire subtrees) that are not ready to be rendered (“suspending”) 👉 What causes a component to be suspending? Fetching data (with a supported library) Loading code (with React’s lazy loading) 👉 Native way to support asynchronous operations in a declarative way (no more isLoading states and render logic 🎉) 1 2 Products App Nav Built-in React component Component in Next.js that will fetch data (will be suspending) Suspense
  • 412. HOW DOES SUSPENSE WORK? App Nav ☝ Important: Components do NOT automatically suspend just because an async operation is happening inside them. Integrating async operations with Suspense is hard, so we use libraries ( React Query, Next.js, etc.) While rendering, suspending component is found Go to closest Suspense parent (“boundary”) and discard already rendered children Display fallback component/JSX Render subtree under Suspense boundary Products Filter List Products Products Filter List Products Filter Suspense AFTER ASYNC WORK IS DONE COMPONENT TREE These haven’t been rendered yet
  • 413. A LOOK BEHIND THE SCENES Another built-in component Fallback Reconciliation + Diffing FIBER TREE REPRESENTATION Triggers Suspense by throwing promise throw new Promise(...) ☝ Fallback will NOT be shown again if the Suspense trigger is wrapped in a transition (startTransition). In Next.js, that’s the case with page navigations. We can reset the Suspense boundary with a unique key prop Suspense App Nav Activity Spinner Filter List Products Sibling Child 🤔 How does Suspense actually know that a component is suspending? Activity = ‘Hidden’ Activity = ‘Visible’ Activity = ‘Visible’ State is preserved in subsequent suspending
  • 415. SECTION LECTURE DATA FETCHING, CACHING, AND RENDERING DIFFERENT TYPES OF SSR : STATIC VS. DYNAMIC RENDERING
  • 416. SERVER - SIDE RENDERING IN NEXT.JS 👉 Next.js is a React framework, so rendering is done by React, following the rules we learned earlier 👉 Remember: Both Server and Client components are rendered on the server on the initial render 👉 In Next.js, the server-side rendering work is split by routes 👉 Each route can be either static (also called pre- rendered) or dynamic 👉 There is also Partial Pre-Rendering ( PPR ) which mixes dynamic and static rendering in the same route (more later 👉) / /search /product Dynamic Static Static Routes of the same app
  • 417. STATIC VS. DYNAMIC RENDERING 👉 HTML is generated at built time, or periodically in the background by re-fetching data ( ISR, more on this later 👉) 👉 Useful when data doesn’t change often and is not personalized to user (e.g. product page) 👉 Default rendering strategy in Next.js (even when a page or component fetches data) 👉 When deployed to Vercel, each static route is automatically hosted on a CDN 👉 If all routes of an app are static, the entire app can be exported as a static site ( SSG ) STATIC RENDERING DYNAMIC RENDERING 👉 HTML is generated at request time (for each new request reaches the server) 👉 Makes sense if: 1⃣ The data changes frequently and is personalized to the user (e.g. cart) 2⃣ Rendering a route requires information that depends on request (e.g. search params) 👉 A route automatically switches to dynamic rendering in certain conditions (next slide 👉) 👉 When deployed to Vercel, each dynamic route becomes a serverless function Content Delivery Network
  • 418. WHEN NEXT.JS SWITCHES TO DYNAMIC RENDERING 👉 Usually, developers don’t directly choose whether a route should be static or dynamic. Next.js will automatically switch to dynamic rendering in the following scenarios: 👉 We can also force Next.js to render a route dynamically: 👉 export const dynamic = ‘force-dynamic’; from page.js 👉 export const revalidate = 0; from page.js 👉 { cache: 'no-store' } added to a fetch request in any of the route’s server components 👉 noStore() in any of the route’s server components 1 The route has a dynamic segment (page uses params) /product?quantity=23 2 searchParams are used in the page component 3 headers() or cookies() are used in any of the route’s server components These influence caching ( 3 ) . More on this later 👉 4 👉 This is necessary because any of these values can not be known by Next.js at built time 4 An uncached data request is made in any of the route’s server components
  • 419. SOME TERMINOLOGY YOU MIGHT NEED 👉 Content Delivery Network ( CDN ) : A network of servers located around the globe that cache and deliver a website’s static content ( HTML, CSS, JS, images) from as close as possible to each user. 👉 Serverless computing: With the serverless computing model, we can run application code, usually back- end code, without managing the server ourselves. Instead, we can just run single functions on a cloud provider: serverless functions. The server is initialized and active only for the duration the serverless function is running, unlike a traditional Node.js app where the server is constantly running. Remember: each dynamic route becomes a serverless function. 👉 The “edge”: “As close as possible to the user”. A CDN is part of an “edge” network, but there is also serverless “edge” computing. This is serverless computing that does not happen on a central server, but on a network that’s distributed around the globe, as close as possible to the user (like a CDN but for running code). Important: we can select certain routes to run on the edge when deployed to Vercel. 👉 Incremental Static Regeneration ( ISR ) : A Next.js feature that allows developers to update the content of a static page, in the background, even after the website has already been built and deployed. This happens by re-fetching the data of a component or entire route after a certain interval. More on this later 👉
  • 421. SECTION LECTURE DATA FETCHING, CACHING, AND RENDERING PARTIAL PRE - RENDERING
  • 422. PARTIAL PRE - RENDERING ( PPR ) : A WHOLE NEW WAY OF RENDERING 👉 Idea/problem: Most pages don’t need to be 100% static or 100% dynamic 👉 Solution: Partial Pre-Rendering 👉 New rendering strategy that combines static and dynamic rendering in the same route /search /product 100% Dynamic / 100% Static PPR 80% static 20% dynamic Static shell Dynamic content “Pre- rendered” 1 2 👉 Result: Even faster pages that can mostly be delivered from the edge ( CDN ) even when there are small dynamic parts. A static (pre-rendered) shell is served immediately from a CDN, leaving holes for dynamic content The slower dynamic content is streamed in as it’s rendered on the server
  • 423. HOW TO USE PARTIAL PRE - RENDERING 👉 PPR needs to be turned on in config file 👉 By default, as much as possible of any route will be statically rendered, creating a static shell 👉 Dynamic parts (components) should be placed inside Suspense boundaries 👉 There are no new APIs to learn 🎉 👉 These boundaries tell Next.js that anything within the boundary is dynamic 👉 The boundary prevents the dynamic part (e.g. reading a header or making a non-cached fetch request) from spreading onto the entire route. 👉 We provide a static fallback to be shown while the dynamic part is rendering 👉 Dynamic components or sub-trees are inserted into the static shell as they become available 👋 As of Next.js 14, PPR is highly experimental and should not be used in production
  • 425. SECTION LECTURE DATA FETCHING, CACHING, AND RENDERING HOW NEXT.JS CACHES DATA
  • 426. NEXT.JS CACHING CACHING IN NEXT.JS 👉 Caching: Storing fetched or computed data in a temporary location for future access, instead of having to re-fetch or re-compute the data every time it’s needed 👉 Next.js caches very aggressively: everything that is possible to cache, is cached 👉 Next.js provides APIs for cache revalidation: removing data from the cache and updating it with fresh data (re-fetched or re-computed) 👍 Makes Next.js apps more performant and saves costs (computing and data access) 👎 Caching always ON by default: strange and unexpected behavior in some situations. Some caches can’t be turned off 🤯 👎 Very confusing: Many different Next.js APIs affect and control caching
  • 427. 🗺 Where? ⏱ How long? 🧩 Enables 💾 What data? THE CACHING MECHANISMS REQUEST MEMOIZATION ROUTER CACHE DATA CACHE FULL ROUTE CACHE Server Server Server Client Data fetched with similar GET requests (same url and options in fetch function) Data fetched in a route or a single fetch request Entire static pages ( HTML and RSC payload) Pre-fetched and visited pages: static and dynamic One page request (one render, one user) Indefinitely, even across de-deploys (can revalidate or opt out) Until the “Data cache” is invalidated (or app is re-deployed) 30 sec dynamic / 5 min static (throughout one user session) No need to fetch at the top of tree: the same fetch in multiple components only makes one request Data for static pages + ISR when revalidated SPA-like navigation (instant navigation and no full reloads) Static pages ⚡ 👩💻 📄 🗄 👋 This is the behavior in production mode. Caching doesn’t work in development Only in components (not route handlers or server actions)
  • 428. THE CACHING MECHANISMS 🔄 How to revalidate? 🙅 How to opt out? N.A. 👉 Time-based (automatic) for all data on page: export const revalidate = <time>; (page.js) 👉 Time-based (automatic) for one data request: fetch('…', { next: { revalidate: <time>} }) 👉 On-demand (manual): revalidatePath or revalidateTag 👉 revalidatePath or revalidateTag in SA 👉 router.refresh 👉 cookies.set or cookies.delete in SA Not possible AbortController 👉 Entire page: export const revalidate = 0; (page.js) 👉 Entire page: export const dynamic = ‘force-dynamic’; (page.js) 👉 Individual request: fetch('…', { cache: 'no-store' }) 👉 Individual server component: noStore() REQUEST MEMOIZATION ROUTER CACHE DATA CACHE FULL ROUTE CACHE These forces page to become dynamic, which also opts out of the Full Route Cache Can be very problematic Revalidating Data Cache also revalidates Full Route Cache ⚡ 👩💻 📄 🗄
  • 431. SECTION LECTURE CLIENT AND SERVER INTERACTIONS BLURRING THE BOUNDARY BETWEEN SERVER AND CLIENT
  • 432. TRADITIONAL THE SERVER - CLIENT BOUNDARY : FRONT - END VS. BACK - END BACK - END [ API ] 🌐 FRONT - END 👩💻 NEXT.JS WITH RSC + SA 👉 No clear separation between front-end and back-end anymore 👉 “Knitting”: pieces of server and client code interweave (composability) 👉 Allow us to build true full-stack applications in just one codebase 👉 No need for an intermediary API in many times 👉 Very clear server-client boundary 👉 Communication happens via an API 👉 Once JSON arrives from the back-end, the front-end takes over JSON DATA [ GET ] MUTATIONS [ POST, PUT …] Server component Client component DATA : RENDER DIRECTLY DATA : SEND AS PROPS MUTATIONS : SERVER ACTIONS ( SA ) FRONT - END FRONT - END BACK - END BACK - END BACK - END FRONT - END BACK - END
  • 433. E ( CC ) C ( SC ) A ( SC ) B ( CC ) D ( SC ) E ( CC ) C ( CC ) DEPENDENCY TREE ( MODULE IMPORTS ) IMPORTING VS. RENDERING 📦 Can import Only client components (can’t go back in client-server boundary) ✍ Can render Client components and server components passed as props CLIENT COMPONENTS SERVER COMPONENTS 👉 Possible if server component is passed as prop (children or other) 👉 D has already been executed here… COMPONENT TREE E ( CC ) C ( CC ) C ( SC ) A ( SC ) B ( CC ) D ( SC ) E ( CC ) renders “use client” “use client” imports 🤔 A client component rendering a server component? 🤔 Is C a server or a client component? 👉 It can be both! A component imported inside the client-server boundary creates a client component instance “use client” Client-server boundary Where client-server boundaries are Client and server components Client and server components C ( SC )
  • 437. HOW MIDDLEWARE WORKS IN NEXT.JS REQUEST RESPONSE MIDDLEWARE
  • 438. HOW MIDDLEWARE WORKS IN NEXT.JS REQUEST 👉 By default, middleware runs before every route in a project, but we can specify which paths using a matcher 👉 Analogy: chunk of code that’s in every page.js component 👉 Only one middleware function: needs to be exported from middleware.js (or .ts) in the project root folder 👉 Middleware needs to produce a response: or RESPONSE APP ROUTES MIDDLEWARE SEND RESPONSE DIRECTLY ( USUALLY JSON ) 2 👉 Read and set cookies and headers 👉 Authentication and authorization 👉 Server-side analytics 👉 Redirect based on geolocation 👉 A/B testing 1 REDIRECT OR REWRITE TO A ROUTE 2 1 USE CASES : MIDDLEWARE DETAILS :
  • 441. SECTION LECTURE WHAT ARE SERVER ACTIONS? MUTATIONS WITH SERVER ACTIONS + MODERN REACT HOOKS
  • 442. WHAT ARE SERVER ACTIONS? SERVER ACTIONS ⚙ SERVER COMPONENTS 📦 SERVER ACTIONS 👉 The missing piece in the RSC architecture that enables interactive full-stack applications 👉 Async functions that run exclusively on the server, allowing us to perform data mutations RSC ARCHITECTURE MUTATIONS 2 DATA FETCHING 1 That is able to handle user input INTERACTIVE FULL - STACK APPLICATIONS 🎯
  • 443. HOW TO CREATE SERVER ACTIONS SERVER 🌐 CLIENT 👩💻 “use server” (“API endpoint”) “use client” (“<script> tag”) NOT for server components, but for server actions 1 An async function in a server component. Can be used in component or passed to a client component (unlike functions) SERVER ACTIONS CAN BE DEFINED AT THE TOP OF : 2 Standalone file: exported functions become server actions that can be imported into any component [recommended] SERVER ACTIONS 👉 The missing piece in the RSC architecture that enables interactive full-stack applications 👉 Async functions that run exclusively on the server, allowing us to perform data mutations 👉 Created with the “use server” directive at the top of the function or an entire module 👉 Behind the scenes: Next.js creates API endpoint (with URL ) for each server action. Whenever a server action is called, a POST request is made to its URL (the function itself never reaches client) 👉 Unlike server components, server actions actually require a running web server We don’t have to manually create APIs or route handlers to mutate data 🎉
  • 444. HOW TO USE SERVER ACTIONS SERVER ACTIONS 👉 The missing piece in the RSC architecture that enables interactive full-stack applications 👉 Async functions that run exclusively on the server, allowing us to perform data mutations 👉 Created with the “use server” directive at the top of the function or an entire module 1 action attribute in a <form> element (in server and client components) SERVER ACTIONS CAN BE CALLED FROM : 2 Event handlers (only client components) 3 useEffect (only client components) IN SERVER ACTIONS, WE CAN : 👉 Perform data mutations (create, update, delete) 👉 Update the UI with new data: Revalidate cache with revalidatePath and revalidateTag 👉 Work with cookies 👉 Many more… 👉 Behind the scenes: Next.js creates API endpoint (with URL ) for each server action. Whenever a server action is called, a POST request is made to its URL (the function itself never reaches client) 👉 Unlike server components, server actions actually require a running web server Code is running on the back-end, so we need to assume inputs are unsafe