Theory Slides v1.1
Theory Slides v1.1
SLIDES FOR
THEORY
LECTURES
DON’T SKIP THEM, THEY ARE
SUPER IMPORTANT 🤓)
Follow me here
(
📖 TABLE OF CONTENTS THEORY LECTURES CLICK THE TITLES
1 Watch Before You Start! 14 State vs. Props 27 How Diffing Works
2 Why Do front-end Frameworks exist? 15 What is "Thinking in React"? 28 The Key Prop
3 What is React? 16 Fundamentals of State Management 29 Rules for Render Logic: Pure components
4 Setting Up a New React Project: The Two Options 17 Derived State 30 State Update Batching
5 Components as Building Blocks 18 The children Prop: Making a Reusable Button 31 How Events Work in React
6 What is JSX? 19 How to Split a UI Into Components 32 Libraries vs. Frameworks & The React Ecosystem
8 Props, Immutability, and One-Way Data Flow 21 Component Composition 34 The Component Lifecycle
10 Section Summary 23 Components, Instances, and Elements 36 The useEffect Dependency Array
11 What is State in React? 24 How Rendering Works: Overview 37 The useEffect Cleanup Function
12 The Mechanics of State 25 How Rendering Works: The Render Phase 38 React Hooks and Their Rules
13 More Thoughts About State State Guidelines 26 How Rendering Works: The Commit Phase 39 useState Summary
+
:
(
)
📖 TABLE OF CONTENTS THEORY LECTURES CLICK THE TITLES
40 Introducing Another Hook: useRef 53 Don't Optimize Prematurely! 66 An Overview of Server-Side Rendering SSR
41 What are Custom Hooks? When to Create One? 54 useEffect Rules and Best Practices 67 The Missing Piece: Hydration
43 Managing State With useReducer 56 Redux Middleware and thunks 69 What are React Server Components? RSC Part 1
44 Section Summary: useState vs. useReducer 57 What is Redux Toolkit RTK ? 70 How RSC Works Behind the Scenes RSC Part 2
45 Routing and Single-Page Applications SPAs) 58 Redux vs. Context API 71 RSC vs. SSR How are They Related? RSC Part 3
46 Styling Options For React Applications 59 Application Planning (“Fast React Pizza Co.”) 72 Project Planning: "The Wild Oasis" Website
47 What is the Context API? 60 What is Tailwind CSS? 73 What is React Suspense?
48 Thinking In React: Advanced State Management 61 Application Planning (“The Wild Oasis”) 74 Types of SSR Static vs. Dynamic Rendering
51 Understanding useMemo and useCallback 64 What is React Query? 77 Blurring the Boundary Between Server and Client
52 Optimizing Bundle Size With Code Splitting 65 An Overview of Reusability in React 78 What is Middleware in Next.js?
LECTURE
WATCH BEFORE YOU START!
SOME QUICK CONSIDERATIONS BEFORE WE 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
😱 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
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
👩💻 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
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!
LECTURE
WHY DO FRONT END
FRAMEWORKS EXIST?
-
THE RISE OF SINGLE PAGE APPLICATIONS
The “old” way (but now
getting modern again…) SERVER SIDE RENDERING
VIEW
RENDER
BROWSER
WEBPAGE
DATA
🌐 SERVER / BACK END 👩💻 CLIENT / FRONT END and more JS code, which led to…
DATA RENDER
API BROWSER
WEBPAGE
VIEW
👉 Single-Page Application SPA
-
-
-
-
(
)
-
SINGLE PAGE APPLICATIONS WITH VANILLA JAVASCRIPT?
DATA
DATA
DATA
DATA
?? ☝ Keeping UI
and data in sync
would be virtually
impossible with
just vanilla
JavaScript
Piece of data
=
Piece of state
SINGLE PAGE APPLICATIONS WITH VANILLA JAVASCRIPT?
Front-end frameworks solve this problem and take hard work away from developers 🎉
They enforce a “correct” way of structuring and writing code (therefore contributing to
2
solving the problem of “spaghetti code” 🍝)
3 They give developers and teams a consistent way of building front-end applications
-
SECTION
A FIRST LOOK AT REACT
LECTURE
WHAT IS REACT?
WHAT IS REACT?
REACT
REACT
Component 1
Component 2 Webpage
Declarative Component 3
JavaScript library
Extremely popular
Created by facebook
REACT IS BASED ON COMPONENTS
NavBar Search
Based on components
Results
Declarative
Listing
State-driven
JavaScript library
Listing
Extremely popular
Listing
Created by facebook Map
REACT IS DECLARATIVE
Based on components
👉 We describe how components
look like and how they work using
JSX returned from a component
Declarative a declarative syntax called JSX
1 RENDER
Declarative STATE UI
4 RE RENDER Search apartments
State-driven 2
3 UPDATE STATE
JavaScript library
Extremely popular
REACT REACTS TO STATE CHANGES
BY RE RENDERING THE UI
Created by facebook
-
-
-
REACT IS A JAVASCRIPT LIBRARY
Based on components
Declarative
JavaScript library
Extremely popular
Based on components
React is extremely
popular
Declarative
State-driven
Weekly downloads from NPM
Created by facebook
✅ Gigantic third-party library ecosystem
(
)
REACT WAS CREATED BY FACEBOOK
Based on components
Declarative
State-driven
Created by facebook
🎯 SUMMARY
2 Keeping the UI in sync with state, by re-rendering (reacting) when state changes
RE RENDER
Component 1
Component 2
Component 3
RENDER
-
(
)
SECTION
A FIRST LOOK AT REACT
LECTURE
SETTING UP A NEW REACT
PROJECT THE TWO OPTIONS
:
THE TWO OPTIONS FOR SETTING UP A RECT PROJECT
👉 Complete “starter kit” for React applications 👉 Modern build tool that contains a template
for setting up React applications
👍 Everything is already configured: ESLint,
Prettier, Jest, etc. Jest 👎 Need to manually set up ESLint (and others)
👎 Uses slow and outdated technologies (i.e. 👍 Extremely fast hot module replacement
webpack) HMR and bundling
👉 react.dev
LECTURE
COMPONENTS AS BUILDING
BLOCKS
COMPONENTS AS BUILDING BLOCKS
COMPONENTS
COMPONENTS
Component A
Component C
👉 Piece of UI that has its own data, logic,
and appearance (how it works and looks)
VideoPlayer
COMPONENTS
QuestionList
COMPONENT TREES
VideoPlayer
App
Menu
Video
Menu
Refine Questions RefineQuestions
Player Questions List
Filters
Filters Question
Question Question
Parent Child
component component Question Question
Question
QuestionList
SECTION
WORKING WITH COMPONENTS,
PROPS, AND JSX
LECTURE
WHAT IS JSX?
WHAT IS JSX?
JSX
Component
Data
👉 Declarative syntax to describe what
components look like and how they work Logic
JSX returned from component
👉 Components must return a block of JSX Appearance
JSX
👉 Describe what UI should look like using JSX, based on current data
LECTURE
SEPARATION OF CONCERNS
SEPARATION OF CONCERNS?
“Traditional” separation
ONE TECHNOLOGY PER FILE
of concerns
Rise of React
JavaScript is in Logic and UI are Why keep them
interactive Components
charge of HTML tightly coupled separated?
SPAs JSX
+
SEPARATION OF CONCERNS?
Component
Data
Logic
Rise of React
JavaScript is in Logic and UI are Why keep them
interactive Components
charge of HTML tightly coupled separated?
SPAs JSX
+
SEPARATION OF CONCERNS!
“Traditional”
separation of
concerns
Each component
is concerned
with one piece
COMPLETELY of the UI
NEW PARADIGM
Question
Menu
Filters
Player
Rise of React
JavaScript is in Logic and UI are Why keep them
interactive Components
charge of HTML tightly coupled separated?
SPAs JSX
+
SECTION
WORKING WITH COMPONENTS,
PROPS, AND JSX
LECTURE
PROPS, IMMUTABILITY, AND ONE
WAY DATA FLOW
-
REVIEWING PROPS
PROPS
App
Pizza Order
Pizza
Pizza
REVIEWING PROPS
PROPS
PROPS
App
ONE WAY DATA FLOW...
👍 … is more performant
Pizza
Pizza
Angular has two-way data flow
-
-
SECTION
WORKING WITH COMPONENTS,
PROPS, AND JSX
LECTURE
THE RULES OF JSX
RULES OF JSX
👉 JSX works essentially like HTML, but we can enter 👉 className instead of HTML’s class
“JavaScript mode” by using {} (for text or attributes)
👉 htmlFor instead of HTML’s for
👉 We can place JavaScript expressions inside {}.
👉 Every tag needs to be closed. Examples: <img />
Examples: reference variables, create arrays or objects,
or <br />
[].map(), ternary operator
1⃣ We can place other pieces of JSX inside {} 👉 CSS inline styles are written like this: {{<style>}}
(to reference a variable, and then an object)
2⃣ We can write JSX anywhere inside a component (in
if/else, assign to variables, pass it into functions) 👉 CSS property names are also camelCased
👉 A piece of JSX can only have one root element. If you 👉 Comments need to be in {} (because they are JS
need more, use <React.Fragment> (or the short <>)
)
SECTION
WORKING WITH COMPONENTS,
PROPS, AND JSX
LECTURE
SECTION SUMMARY
🎯 SECTION SUMMARY
Components in
To pass data from parent
component tree
to child components App Component
Props Data
JS Logic
“HTML”
List of
Pizza
Pizzas
Components can be
conditionally rendered JSX block is what
Pizza using JS tools: &&, ?, we return from a
and multiple return component
STATE, EVENTS, AND
FORMS INTERACTIVE
COMPONENTS
:
SECTION
STATE, EVENTS, AND FORMS
INTERACTIVE COMPONENTS
LECTURE
WHAT IS STATE IN REACT?
:
📚 WHAT WE NEED TO LEARN
👉 useState
👉 useReducer
👋 State is the most important
concept in React
👉 Context API Rest of the
course...
So we will keep learning about state
3 Thinking about state
throughout the entire course…)
👉 When to use state
👉 Where to place state
👉 Types of state
(
:
WHAT IS STATE?
Parent
STATE Component
🧠
Props
👉 “Component’s memory” Data
State
Logic
Appearance
WHAT IS STATE?
STATE
👉 “Component’s memory”
🧠
👉 “State variable” / “piece of state” A single
variable in a component (component state)
Parent
STATE Component
🧠
Props
👉 “Component’s memory” Data
Component
State
View
👉 Component state: Single local component
variable (“Piece of state”, “state variable”)
Logic
STATE
STATE ALLOWS DEVELOPERS TO
👉 Data that a component can hold over time,
necessary for information that it needs to
remember throughout the app’s lifecycle
Update the component’s
1
view (by re-rendering it)
👉 “Component’s memory”
🧠 Persist local variables between
2
👉 Component state: Single local component renders
variable (“Piece of state”, “state variable”)
LECTURE
THE MECHANICS OF STATE
:
THE MECHANICS OF STATE IN REACT
RENDER / UPDATED
STATE VIEW
RE RENDER VIEW
👉 State is preserved
React calls the
throughout re-renders
component
function again
-
THE MECHANICS OF STATE IN REACT
3 RE RENDER
2 UPDATE STATE
-
-
THE MECHANICS OF STATE IN REACT
RE RENDER
UPDATE STATE
-
THE MECHANICS OF STATE IN REACT
LECTURE
MORE THOUGHTS ABOUT STATE
STATE GUIDELINES
+
:
ONE COMPONENT, ONE STATE
score = 2
0
1 score = 0 score = 1
0
0
2
1 0 0
1
UI AS A FUNCTION OF STATE
Component A
Component B
UI = f(state )
Component C
Component D
STATE
TIME
UI
👉 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 {}
👉 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”)
👉 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.
👉 When building a component, imagine its view as a reflection of state changing over time
👉 For data that should not trigger component re-renders, don’t use state. Use a regular variable
instead. This is a common beginner mistake.
SECTION
STATE, EVENTS, AND FORMS
INTERACTIVE COMPONENTS
LECTURE
STATE VS. PROPS
:
STATE VS. PROPS
STATE PROPS
Parent state
update
:
SECTION
THINKING IN REACT STATE
MANAGEMENT
LECTURE
WHAT IS "THINKING IN REACT"?
:
“THINKING IN REACT” IS A CORE SKILL
THINKING IN REACT
👉 “React Mindset”
HOW TO
THINKING IN 👉 Thinking about components,
WORK WITH
REACT state, data flow, effects, etc.
REACT API
👉 Thinking in state transitions, not
element mutations
2 Build a static version in React (without state) 🤔 How to make some components reusable?
LECTURE
FUNDAMENTALS OF STATE
MANAGEMENT
:
WHAT IS STATE MANAGEMENT?
isOpen
PIECES OF
STATE coupons
searchQuery user
(useState)
notifications
shoppingCart language
TYPES OF STATE LOCAL VS. GLOBAL STATE
👉 State needed only by one or few components 👉 State that many components might need
👉 State that is defined in a component and only 👉 Shared state that is accessible to every
that component and child components have component in the entire application
access to it (by passing via props)
Global state
Local state
:
STATE WHEN AND WHERE?
NO
Need to store data Will data change at some point? Regular const variable
YES
YES
Can be computed from existing state/props? Derive state
“Always start
with local state” NO
NO
Should it re-render component? Ref (useRef, more on this later)
YES
WHEN TO CREATE STATE
Place a new piece of state in component
WHERE TO PLACE STATE
YES
Only used by this component? Leave in component
NO
YES
Also used by a child component? Pass to child via props
NO
NO YES
👉 Probably global state. Global state
Used by one or a few sibling components? Lift state up to first common parent
management later in the course...
:
SECTION
THINKING IN REACT STATE
MANAGEMENT
LECTURE
REVIEWING "LIFTING UP STATE"
:
PROBLEM SHARING STATE WITH SIBLING COMPONENT
props props
setCoupons coupons
props props
coupons
LECTURE
DERIVED STATE
:
DERIVING STATE
DERIVING STATE
👍 Derived state: state that is computed from
an existing piece of state or from props
LECTURE
THE CHILDREN PROP MAKING A
REUSABLE BUTTON
:
:
THE CHILDREN PROP
Button
props.children
Children of Button,
accessible through
props.children
👉 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)
PART 02
—
INTERMEDIATE
REACT
THINKING IN REACT
COMPONENTS,
COMPOSITION, AND
REUSABILITY
:
SECTION
THINKING IN REACT
COMPONENTS, COMPOSITION,
AND REUSABILITY
LECTURE
HOW TO SPLIT A UI INTO
COMPONENTS
:
COMPONENT SIZE MATTERS
COMPONENT SIZE
SMALL HUGE
👉 Hard to reuse
Many small
components 0
0
COMPONENT SIZE
0 ✅ Logical separation
2. Reusability
✅ Some are reusable
0 ✅ Low complexity
3. Responsibilities
/ complexity
👎
0
0
4. Personal
coding style 0
FRAMEWORK WHEN TO CREATE A NEW COMPONENT?
💡 SUGGESTION When in doubt, start with a relatively big component, Skip if you're sure you
then split it into smaller components as it becomes necessary need to reuse. But
otherwise, you don’t need
to focus on reusability
and complexity early on
1. Logical separation 👉 Does the component contain pieces of content or layout
of content/layout that don’t belong together?
🗃 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... 👉)
(
ANY APP HAS COMPONENTS OF DIFFERENT SIZES AND REUSABILITY
0
👉 Page component
👉 Some very small components are necessary! 👉 Most apps will have a few huge components
👉 Highly reusable 👉 Not meant to be reused (not a problem!
👉 Very low complexity
-
)
SECTION
THINKING IN REACT
COMPONENTS, COMPOSITION,
AND REUSABILITY
LECTURE
COMPONENT CATEGORIES
:
COMPONENT CATEGORIES
👉 Most of your components will naturally fall into one of three categories:
Stateless /
Stateful Structural
presentational
components components
components
LECTURE
COMPONENT COMPOSITION
:
WHAT IS COMPONENT COMPOSITION?
Want to
reuse
COMPONENT COMPOSITION
👉 Component composition: combining
different components using the
children prop (or explicitly defined
Modal Error props)
LECTURE
PROPS AS A COMPONENT API
:
PROPS AS AN API
Component
Component props Public API
👩💻
COMPONENT
Consuming
component
🎛 🧑💻
👩💻
COMPONENT
CONSUMER App Abstraction that CREATOR
encapsulates UI and logic
TOO LITTLE PROPS We need to find the right TOO MANY PROPS
balance between too little
👉 Not flexible enough and too many props, that 👉 Too hard to use
👉 Might not be useful works for both the 👉 Exposing too much complexity
consumer and the creator
👉 Hard-to-write code
👉 Provide good default values
=
GOT QUESTIONS? FEEDBACK?
JUST POST IT IN THE Q&A OF
THIS VIDEO, AND YOU WILL
GET HELP THERE!
HOW REACT WORKS
BEHIND THE SCENES
SECTION
HOW REACT WORKS BEHIND THE
SCENES
LECTURE
COMPONENTS, INSTANCES, AND
ELEMENTS
COMPONENT VS. INSTANCE VS. ELEMENT
Component
👉 Description of a piece of UI
👉 “Blueprint” or “Template”
COMPONENT VS. INSTANCE VS. ELEMENT
Component
Component Instance
Instances of Tab
Component
Component Instance
REACT ELEMENT
RETURNS
React Element
👉 JSX is converted to React.createElement() function calls
Component
Component Instance
RETURNS
INSERTED TO DOM
LECTURE
HOW RENDERING WORKS
OVERVIEW
:
QUICK RECAP BEFORE WE GET STARTED
User
Component React DOM Element Interface on
Instance A3 Element HTML the screen
.
.
.
☝ 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.
:
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
[
]
:
SECTION
HOW REACT WORKS BEHIND THE
SCENES
LECTURE
HOW RENDERING WORKS THE
RENDER PHASE
:
REVIEW THE MECHANICS OF STATE IN REACT
3 RE RENDER
2 UPDATE STATE
2 RENDER PHASE
Component
instances that React Elements
triggered re-render
New
Virtual DOM
[
]
THE VIRTUAL DOM REACT ELEMENT TREE
B C D B C D
E E E E
-
:
(
)
THE VIRTUAL DOM REACT ELEMENT TREE
B C D B C D 👉
2 RENDER PHASE
Component
instances that React Elements
triggered re-render
New
Virtual DOM
Reconciler
called “Fiber”
Current
Reconciliation Updated
Fiber tree
Diffing Fiber tree
(before state update)
[
+
]
WHAT IS RECONCILIATION AND WHY DO WE NEED IT?
BECAUSE
HOW?
App App
REACT
ELEMENT Video Modal Btn Video Modal Btn
FIBER
TREE
TREE
VIRTUAL Overlay ON INITIAL Overlay
DOM RENDER
h3 button h3 button
FIBER
👉 Fiber tree: internal tree that has a “Unit of work”
👉 Rendering process can be split into
“fiber” for each component
chunks, tasks can be prioritized, and work Current state
instance and DOM element can be paused, reused, or thrown away
Props
👉 Fibers are NOT re-created on 👉 Enables concurrent features like
Side effects
every render Suspense or transitions
Used hooks
👉 Work can be done asynchronously 👉 Long renders won’t block JS engine
Queue of work
(
)
:
RECONCILIATION IN ACTION
2 RENDER PHASE
Component
instances that React Elements
triggered re-render
New
Virtual DOM Result of the
Reconciler render phase
called “Fiber” (“list of effects”)
Current
Reconciliation Updated List of DOM
Fiber tree
Diffing Fiber tree updates
(before state update)
[
+
]
SECTION
HOW REACT WORKS BEHIND THE
SCENES
LECTURE
HOW RENDERING WORKS THE
COMMIT PHASE
:
THE COMMIT PHASE AND BROWSER PAINT
React ReactDOM
React ReactDOM
“RENDERERS”
Many others…
React can be used on
different platforms (“hosts”) Terrible name! Renderers do not render, they commit the result of render phase…
[
[
[
]
]
]
RECAP PUTTING IT ALL TOGETHER
LECTURE
HOW DIFFING WORKS
THE RENDER PHASE
2 RENDER PHASE
Component
instances that React Elements
triggered re-render
Current
Reconciliation Updated List of DOM
Fiber tree
Diffing Fiber tree updates
(before state update)
[
+
]
HOW DIFFING WORKS
Two elements of
1 different types will
Different
produce different trees
DOM element
Two elements of
1 different types will
Same DOM
produce different trees
element
👉 Sometimes this is not what we want… Then we can use the key prop
[
SECTION
HOW REACT WORKS BEHIND THE
SCENES
LECTURE
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)
👉 Same elements, but different position in 👉 Different position in the tree, but the key
tree, so they are removed and recreated stays the same, so the elements will be
in the DOM (bad for performance) kept in the DOM 👉 Always use keys!
[
]
2. KEY PROP TO RESET STATE CHANGING KEY
NEW QUESTION IN
SAME POSITION
State was
preserved. NOT
what we want
[
]
2. KEY PROP TO RESET STATE CHANGING KEY
NEW QUESTION IN
SAME POSITION
State was
RESET
[
]
SECTION
HOW REACT WORKS BEHIND THE
SCENES
LECTURE
RULES FOR RENDER LOGIC PURE
COMPONENTS
:
THE TWO TYPES OF LOGIC IN REACT COMPONENTS
1. RENDER LOGIC
✅ Pure function
☝ 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 update state (or refs): this will create an infinite loop!
LECTURE
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 = ''
solved = false
🤔
At this point, re-render has not
happened yet
“Stale state”
👉 This also applies when only one state variable is updated UPDATING STATE IN REACT IS
ASYNCHRONOUS
👉 If we need to update state based on previous update, we
use setState with callback (setAnswer(answer=>...))
BATCHING BEYOND EVENT HANDLER FUNCTIONS
EVENT HANDLERS ✅ ✅
TIMEOUTS ❌ ✅
PROMISES ❌ ✅
NATIVE EVENTS ❌ ✅
+
SECTION
HOW REACT WORKS BEHIND THE
SCENES
LECTURE
HOW EVENTS WORK IN REACT
DOM REFRESHER EVENT PROPAGATION AND DELEGATION
DOM tree (not
EVENT Fiber tree or React
DOCUMENT element tree) EVENT DELEGATION
<html>
CAPTURING BUBBLING
1 3 👉 Handling events for multiple elements
PHASE PHASE
<body>
centrally in one single parent element
👉 By default, event
handlers listen to events <div>
👉 Better for performance and memory,
on the target and during #root as it needs only one handler function
the bubbling phase
H
<header>
👉 We can prevent .topbar 1 Add handler to parent (.options)
bubbling with
e.stopPropagation() <div> 2 Check for target element (e.target)
.options
3 If target is one of the <button>s,
<button> <button> <button> handle the event
.btn .btn .btn
H H H
👋 Very common in vanilla JS apps,
2 TARGET ELEMENT but not so much in React apps
:
HOW REACT HANDLES EVENTS
Usually div#root, but
can be any DOM element WHEN WE ATTACH AN EVENT HANDLER...
PointerEvent
MouseEvent 👉 Wrapper around the DOM’s native event object
EVENT 👉 Attributes for event handlers are named using camelCase (onClick instead of onclick or click)
HANDLERS IN 👉 Default behavior can not be prevented by returning false (only by using preventDefault())
VS. 👉 Attach “Capture” if you need to handle during capture phase (example: onClickCapture)
SECTION
HOW REACT WORKS BEHIND THE
SCENES
LECTURE
LIBRARIES VS. FRAMEWORKS &
THE REACT ECOSYSTEM
FIRST, AN ANALOGY 🍣
👍 Ease of mind: All ingredients are included 👍 Freedom: You can choose the best ingredients
👎 No choice: You’re stuck with the kit’s ingredients 👎 Decision fatigue: You need to research and buy
all ingredients separately
-
-
FIRST, AN ANALOGY 🍣
👍 Ease of mind: All ingredients are included 👍 Freedom: You can choose the best ingredients
👎 No choice: You’re stuck with the kit’s ingredients 👎 Decision fatigue: You need to research and buy
all ingredients separately
-
-
FRAMEWORK VS. LIBRARY
“Separate
“All-in-one kit” ingredients”
FRAMEWORK LIBRARY
LARGE SCALE ANGULAR APP LARGE SCALE REACT APP External libraries
👍 Ease of mind: Everything you need to build a 👍 Freedom: You can (or need to) choose multiple
complete application is included in the framework 3rd-party libraries to build a complete application
(“batteries included”)
👎 Decision fatigue: You need to research,
👎 No choice: You’re stuck with the framework’s tools download, learn, and stay up-to-date with
and conventions (which is not always bad! multiple external libraries
-
-
)
REACT 3RD PARTY LIBRARY ECOSYSTEM
5 Styling
6 Form management
7 Animations/transitions
8 UI components
-
FRAMEWORKS BUILT ON TOP OF REACT
External libraries
LECTURE
SECTION SUMMARY PRACTICAL
TAKEAWAYS
:
🎯 PRACTICAL SUMMARY
🧩 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
EFFECTS AND DATA
FETCHING
SECTION
EFFECTS AND DATA FETCHING
LECTURE
THE COMPONENT LIFECYCLE
COMPONENT INSTANCE LIFECYCLE
🐣 🐓 Optional)
💀
MOUNT / RE RENDER
UNMOUNT
INITIAL RENDER
👉 Fresh state and props are 👉 State changes 👉 State and props are
created 👉 Props change destroyed
👉 Parent re-renders
LECTURE
A FIRST LOOK AT EFFECTS
WHERE TO CREATE SIDE EFFECTS
We need side effects all the
time. They make our
SIDE EFFECT applications do something.
Not in render logic!
(can be made in...)
Triggered by EVENTS Triggered by
onClick, onSubmit, etc. RENDERING
Sometimes this is
not enough for the 👉 Effects allow us to
application’s needs write code that will
EVENT EFFECTS
run at different
HANDLERS (useEffect)
moments: mount, re-
render, or unmount
👉 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
Produce the same result,
but at different moments
EVENT HANDLERS EFFECTS useEffect)
Effect
Cleanup
function
🤔 When?
Dependency array
👉 Executed when the corresponding event 👉 Executed after the component mounts (initial
happens render), and after subsequent re-renders
Thinking about
synchronization,
(according to dependency array)
👉 Used to react to an event not lifecycles
👉 Used to keep a component synchronized
with some external system (in this example,
☝ Preferred way of creating side effects!
with the API movie data)
LECTURE
THE USEEFFECT DEPENDENCY
ARRAY
WHAT’S THE USEEFFECT DEPENDENCY ARRAY?
title
CHANGES EFFECT IS DOCUMENT
EXECUTED TITLE
userRating AGAIN IS UPDATED
CHANGES
EFFECT IS
DEPENDENCY EXECUTED AGAIN Effects and
STATE OR PROPS component lifecycle
CHANGES COMPONENT IS are deeply connected
RE RENDERED
👉 We can use the dependency array to run effects when the component renders or re-renders
🔄 SYNCHRONIZATION 🐣 LIFECYCLE
EFFECT ✨
title CHANGES
title = ‘Interstellar Wars’
RE RENDER
COMMIT
Another type of effect
LAYOUT EFFECT
that is very rarely necessary
BROWSER PAINT (useLayoutEffect)
EFFECT ✨
UNMOUNT
time
-
(
)
SECTION
EFFECTS AND DATA FETCHING
LECTURE
THE USEEFFECT CLEANUP
FUNCTION
WHEN ARE EFFECTS EXECUTED?
title = ‘Interstellar’ MOUNT INITIAL RENDER
COMMIT
BROWSER PAINT
EFFECT ✨
title CHANGES
title = ‘Interstellar Wars’
RE RENDER
COMMIT
LAYOUT EFFECT
BROWSER PAINT
CLEANUP 🧹
EFFECT ✨
UNMOUNT
CLEANUP 🧹
time
-
(
)
THE CLEANUP FUNCTION
COMPONENT Execute
👉 Runs on two different occasions:
UNMOUNTS cleanup function
1 Before the effect is executed again
Examples
✨ EFFECT 🧹 POTENTIAL
👉 Necessary whenever the side effect keeps CLEANUP
happening after the component has been
re-rendered or unmounted 👉 HTTP request Cancel request
LECTURE
REACT HOOKS AND THEIR RULES
WHAT ARE REACT HOOKS?
REACT HOOKS
👉 Many more…
👉 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
👉 useReducer 👉 useMemo
👉 useContext 👉 useTransition
👉 useDeferredValue
❌ useLayoutEffect
❌ useDebugValue
FIBER
Props
..
.
ON INITIAL
RENDER List of hooks
REACT ELEMENT TREE FIBER TREE
FIBER
Props
..
.
ON INITIAL
RENDER List of hooks
REACT ELEMENT TREE FIBER TREE
👍 Correct code! 1
State A State A
RENDER
1
2
State B State B
SAME
2
3 ORDER
Effect Z Effect Z
3
LECTURE
USESTATE SUMMARY
SUMMARY OF DEFINING AND UPDATING STATE
Simple
CREATING
1 STATE
Based on function
(lazy evaluation)
Simple
UPDATING
2 STATE
Based on current state
👉 Function must be pure and return next state
SECTION
CUSTOM HOOKS, REFS, AND
MORE STATE
LECTURE
INTRODUCING ANOTHER HOOK
USEREF
:
WHAT ARE REFS?
STATE ✅ ✅ ✅ ✅
REFS ✅ ❌ ❌ ❌
NO
Need to store data Will data change at some point? Regular const variable
YES
Examples: preserving
State (useState) previous state, or storing
the id of a setTimeout
(
-
SECTION
CUSTOM HOOKS, REFS, AND
MORE STATE
LECTURE
WHAT ARE CUSTOM HOOKS?
WHEN TO CREATE ONE?
REUSING LOGIC WITH CUSTOM HOOKS
UI LOGIC
NO YES
REGULAR CUSTOM
COMPONENT
FUNCTION HOOK
LECTURE
CLASS COMPONENTS VS.
FUNCTION COMPONENTS
:
-
FUNCTION COMPONENTS VS. CLASS COMPONENTS
💎 How to create JavaScript function (any type) ES6 class, extending React.Component
💅 Returning JSX Return JSX from function Return JSX from render method
LECTURE
MANAGING STATE WITH
USEREDUCER
WHY USEREDUCER?
When multiple state updates need to happen at the same time (as a
2
reaction to the same event, like “starting a game”)
:
MANAGING STATE WITH USEREDUCER
useReducer
RETURNS
NEXT
dispatch reducer RE RENDER
STATE
action
type = ‘updateDay’ Object that contains information on
payload = 23 how the reducer should update state
useState
UPDATE
NEXT UPDATED
setState RE RENDER
STATE
UPDATED STATE
-
-
(
)
A MENTAL MODEL FOR REDUCERS
LECTURE
SECTION SUMMARY USESTATE
VS. USEREDUCER
:
USESTATE VS. USEREDUCER
useState useReducer
👉 Ideal for single, independent pieces of 👉 Ideal for multiple related pieces of state
state (numbers, strings, single arrays, etc.) and complex state (e.g. object with many
values and nested objects or arrays)
👉 Logic to update state is placed directly in 👉 Logic to update state lives in one central
event handlers or effects, spread all over place, decoupled from components: the
one or multiple components reducer
YES
Just one piece of state?
NO
NO
YES
Over 3 or 4 pieces of related Are you willing to implement NO
state, including objects? slightly more complex code?
NO YES
useState
☝ useState should remain your
default choice for managing state
REACT ROUTER
BUILDING SINGLE
PAGE APPLICATIONS
SPA
(
)
:
-
SECTION
REACT ROUTER BUILDING SINGLE
PAGE APPLICATIONS SPA
LECTURE
ROUTING AND SINGLE PAGE
APPLICATIONS SPAS
(
:
(
)
-
)
WHAT IS ROUTING?
“Client-side 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
(
SINGLE PAGE APPLICATIONS SPA
LECTURE
STYLING OPTIONS FOR REACT
APPLICATIONS
:
(
)
STYLING OPTIONS IN REACT
React doesn’t care about styling
STYLING OPTION WHERE? HOW? SCOPE BASED ON
Local
👉 Inline CSS JSX elements style prop JSX element CSS
👋 Alternative to styling with CSS UI libraries like MUI, Chakra UI, Mantine, etc.
:
SECTION
REACT ROUTER BUILDING SINGLE
PAGE APPLICATIONS SPA
LECTURE
STORING STATE IN THE URL
:
(
)
THE URL FOR STATE MANAGEMENT
👉 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
2 Good way to “pass” data from one page into the next page
3 Makes it possible to bookmark and share the page with the exact UI state it had at the time
www.example.com/app/cities/lisbon?lat=38.728&lng=-9.141
www.example.com/app/cities/lisbon?lat=38.728&lng=-9.141
www.example.com/app/cities/berlin?lat=52.536&lng=13.377
:
ADVANCED STATE
MANAGEMENT THE
CONTEXT API
:
SECTION
ADVANCED STATE MANAGEMENT
THE CONTEXT API
LECTURE
WHAT IS THE CONTEXT API?
:
A SOLUTION TO PROP DRILLING
B D E B D E
F F
👋 Remember that a good solution to “prop drilling” is better component composition (see “Thinking in React” section)
:
:
:
:
WHAT IS THE CONTEXT API?
CONTEXT API
READ VALUE value READ VALUE
Provider
ER
👉 System to pass data throughout the app
ND
RE
without manually passing props down the tree App
RE
RE
RE
ND
👉 Allows us to “broadcast” global state to the
ER
A C
entire app
LECTURE
THINKING IN REACT ADVANCED
STATE MANAGEMENT
:
:
REVIEW WHAT IS STATE MANAGEMENT?
STATE
👉 Needed only by one or few 👉 Might be needed by many
ACCESSIBILITY components components
NO
“If this component was
👉 Only accessible in component 👉 Accessible to every
rendered twice, should a
state update in one of them and child components component in the application
reflect in the other one?”
STATE
👉 All application data loaded 👉 Everything else 😅
DOMAIN from a remote server API
👉 Theme, list filters, form data, etc.
👉 Usually asynchronous
👉 Usually synchronous and stored
👉 Needs re-fetching + updating in the application
(
)
STATE PLACEMENT OPTIONS
🗃 3rd-party library Redux, React Query, SWR, Zustand, etc. Global state (remote or UI
👩💻 Browser Local storage, session storage, etc. Storing data in user’s browser
+
)
STATE MANAGEMENT TOOL OPTIONS
🪄 UI STATE
👉 useRef 👉 React Router
LECTURE
PERFORMANCE OPTIMIZATION
AND WASTED RENDERS
PERFORMANCE OPTIMIZATION TOOLS
👋 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: Creates the false
impression that
changing props
re-renders a
🧠 🌐 👪 component. This
is NOT true.
STATE CONTEXT PARENT
CHANGES CHANGES RE RENDERS
👋 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.
Usually no problem, as
React is very fast!
👉 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
-
-
SECTION
PERFORMANCE OPTIMIZATION
AND ADVANCED USEEFFECT
LECTURE
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.
P U T S
NEW IN New calculated
Call Call result
Store
function A function A function A
result
SAME Cached result
IN PUTS
Cache
LECTURE
UNDERSTANDING USEMEMO AND
USECALLBACK
AN ISSUE WITH MEMO
THEREFORE
SOLUTION
LECTURE
OPTIMIZING BUNDLE SIZE WITH
CODE SPLITTING
THE BUNDLE AND CODE SPLITTING
👉 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”)
SECTION
PERFORMANCE OPTIMIZATION
AND ADVANCED USEEFFECT
LECTURE
DON'T OPTIMIZE PREMATURELY!
DON'T OPTIMIZE PREMATURELY!
DO DON’T!
✅ Memoize context value + child components 🚫 Don’t optimize context if it’s not slow
and doesn’t have many consumers
✅ Implement code splitting + lazy loading
for SPA routes
)
SECTION
PERFORMANCE OPTIMIZATION
AND ADVANCED USEEFFECT
LECTURE
USEEFFECT RULES AND BEST
PRACTICES
USEEFFECT DEPENDENCY ARRAY RULES
Reactive value: state, prop, or context value, or
DEPENDENCY ARRAY RULES any other value that references a reactive value
👉 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)
🎯 OTHER STRATEGIES
👉 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
WHEN NOT TO USE AN EFFECT
Fetching data on component mount. This is fine in small apps, but in real-world
2
app, a library like React Query should be used
LECTURE
INTRODUCTION TO REDUX
(
)
WHAT IS REDUX?
REDUX
☝ You need to have a really good understanding of the useReducer hook in order to understand Redux!
(
)
(
)
+
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.
2 You will encounter Redux code in your job, so you should understand it
👋 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.
EVENT HANDLER
dispatch
IN COMPONENT
action
type = ‘deposit’
payload = 50
NEXT
RE RENDER reducer
STATE
CURRENT
STATE
-
THE MECHANISM OF REDUX
action
type = ‘deposit’
payload = 50
EVENT HANDLER
dispatch
IN COMPONENT
reducer
NEXT reducer
RE RENDER
STATE ...
reducer
Each reducer is a pure function that calculates the next state (state CURRENT
transition) based on the action and the current state. Usually one STATE
reducer per app feature (e.g. shopping cart + user data + theme)
-
THE MECHANISM OF REDUX
reducer
NEXT reducer
RE RENDER
STATE ...
reducer
reducer
NEXT reducer
RE RENDER
STATE ...
reducer
CURRENT
👉 REAL WORLD TASK DEPOSITING STATE
$50 INTO YOUR BANK ACCOUNT
-
-
:
SECTION
REDUX AND MODERN REDUX
TOOLKIT WITH THUNKS
LECTURE
REDUX MIDDLEWARE AND
THUNKS
(
)
WHAT IS REDUX MIDDLEWARE?
🤔 Where to make an asynchronous API call (or any other async operation) in Redux?
🤔 Where to make an asynchronous API call (or any other async operation) in Redux?
action action
type = ‘deposit’ type = ‘deposit’
payload = 50 payload = {data}
THUNK
COMPONENT dispatch STORE
MIDDLEWARE
LECTURE
WHAT IS REDUX TOOLKIT RTK ?
(
)
(
)
WHAT IS REDUX TOOLKIT?
REDUX TOOLKIT
👉 Allows us to write a lot less code to achieve the same result (less “boilerplate”)
LECTURE
REDUX VS. CONTEXT API
(
)
CONTEXT API VS. REDUX
👎 Additional state “slide” requires new context 👍 Once set up, it’s easy to create additional state
set up from scratch (“provider hell” in App.js) “slices”
👉 When you just need to share a value that 👉 When you have lots of global UI state that
doesn’t change often Color theme, needs to be updated frequently (because
preferred language, authenticated user, …] Redux is optimized for this) [Shopping cart,
current tabs, complex filters or search, …]
👉 When you need to solve a simple prop
drilling problem 👉 When you have complex state with nested
objects and arrays (because you can
👉 When you need to manage state in a local mutate state with Redux Toolkit)
sub-tree of the app
For example in the compound component pattern
👋 There is no right answer that fits every project. It all depends on the project needs!
+
[
PART 04
—
PROFESSIONAL
REACT
DEVELOPMENT
REACT ROUTER WITH
DATA LOADING V6.4
(
+
)
SECTION
REACT ROUTER WITH DATA
LOADING V6.4
LECTURE
APPLICATION PLANNING
(
+
)
THE PROJECT 🍕 FAST REACT PIZZA CO.
👉 This works well for small apps with one page and a few features
👉 Design and build a static version (no state yet) From earlier
STEP 1
👉 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 ✅ DONE
👉 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
👉 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
FEATURES PAGES
STEP 2 3
1⃣ User 1⃣ Homepage /
STEP 3 4
STATE 1⃣ User Global UI state (no accounts, so stays in app)
“DOMAINS” /
“SLICES” 2⃣ Menu Global remote state (menu is fetched from API
TYPES OF
STATE
3⃣ Cart Global UI state (no need for API, just stored in app)
These usually map
quite nicely to the 4⃣ Order Global remote state (fetched and submitted to API
app features
This is just one of many tech
stacks we could have chosen
👉 Routing The standard for React SPAs
New way of fetching data right inside React Router (v6.4 that is
👉 Remote state
worth exploring (“render-as-you-fetch” instead of “fetch-on-
management render”). Not really state management, as it doesn't persist state.
👉 UI State State is fairly complex. Redux has many advantages for UI state.
management Also, we want to practice Redux a bit more
+
+
)
)
+
)
TAILWIND CSS CRASH
COURSE STYLING
THE APP
:
SECTION
TAILWIND CSS CRASH COURSE
STYLING THE APP
LECTURE
WHAT IS TAILWIND CSS?
:
WHAT IS TAILWIND CSS?
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
(
)
THE GOOD AND BAD ABOUT TAILWIND
👍 You don’t need to think about class names 👎 Markup HTML or JSX looks very unreadable,
with lots of class names (you get used to it)
👍 No jumping between files to write markup and
styles 👎 You have to learn a lot of class names (but
after a day of usage you know fundamentals)
👍 Immediately understand styling in any project
that uses tailwind 👎 You need to install and set up tailwind on each
new project
👍 Tailwind is a design system: many design
decisions have been taken for you, which 👎 You’re giving up on “vanilla CSS” 😢
makes UIs look better and more consistent
👍 Saves a lot of time, e.g. on responsive design 👋 Many people love to hate on tailwind
for no reason. Please don’t be that
👍 Docs and VS Code integration are great
person! Try it before judging 🙏
(
)
SETTING UP OUR
BIGGEST PROJECT
STYLED
COMPONENTS
+
SECTION
SETTING UP OUR BIGGEST
PROJECT STYLED COMPONENTS
LECTURE
APPLICATION PLANNING
+
THE PROJECT THE WILD OASIS
STEP 2 3
FEATURE CATEGORIES NECESSARY PAGES
👉 Used to build Single-Page Applications SPAs) 👉 Used to build Multi-Page Applications MPAs)
👉 All HTML is rendered on the client 👉 Some HTML is rendered in the server
👉 All JavaScript needs to be downloaded before 👉 More performant, as less JavaScript needs to
apps start running: bad for performance be downloaded
👉 One perfect use case: apps that are used 👉 The React team is moving more and more in
“internally” as tools inside companies, that are this direction
entirely hidden behind a login
STEP 4
👉 Routing The standard for React SPAs
👉 Other tools React icons / React hot toast / Recharts / date-fns / Supabase
SUPABASE CRASH
COURSE BUILDING A
BACK END!
-
:
SECTION
SUPABASE CRASH COURSE
BUILDING A BACK END!
LECTURE
WHAT IS SUPABASE?
-
:
WHAT IS SUPABASE?
LECTURE
MODELING APPLICATION STATE
-
:
MODELING STATE
1⃣ Bookings 1⃣ Bookings
2⃣ Cabins 2⃣ Cabins
3⃣ Guests 3⃣ Guests
4⃣ Settings 4⃣ Dashboard
5⃣ Users 5⃣ Check in and out
6⃣ App settings
7⃣ Authentication
👉 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
👉 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
)
REACT QUERY
MANAGING REMOTE
STATE
:
SECTION
REACT QUERY MANAGING
REMOTE STATE
LECTURE
WHAT IS REACT QUERY?
:
WHAT IS REACT QUERY?
REACT QUERY
API
👉 Pre-fetching
👉 Easy remote state mutation (updating)
👉 Offline support
fetch(“api.com fetch(“api.com
👉 Needed because remote state is fundamentally /cabins”) /cabins”)
different from regular UI state
COMPONENT A COMPONENT B
(
)
ADVANCED REACT
PATTERNS
SECTION
ADVANCED REACT PATTERNS
LECTURE
AN OVERVIEW OF REUSABILITY IN
REACT
HOW TO REUSE CODE IN REACT?
To customize the
component’s content Render props pattern
👋 There are even more patterns, For very self-contained components that need/want to manage their
but these ones matter most own state. Compound components are like fancy super-components
PART 05
—
FULL STACK
REACT
-
OVERVIEW OF NEXT.JS
WITH THE "APP"
ROUTER
SECTION
OVERVIEW OF NEXT.JS WITH THE
"APP" ROUTER
LECTURE
AN OVERVIEW OF SERVER SIDE
RENDERING SSR
(
)
-
REVIEW THE RISE OF SINGLE PAGE APPLICATIONS
RENDER
BROWSER
WEBPAGE
RENDER
API BROWSER
WEBPAGE
-
-
:
-
-
-
CLIENT SIDE RENDERING CSR VS. SERVER SIDE RENDERING SSR
👉 HTML is rendered on the client (the user’s 👉 HTML is rendered on the server (the
computer) using JavaScript developer’s computer)
👉 Data is fetched after components mount 👉 Data is fetched before HTML is rendered
👍 Highly interactive: All the code and content 👎 Less interactive: Pages might be downloaded
has already been loaded (except data) on demand and require full page reloads
👉 SPAs: Perfect for building highly interactive 👉 Content-driven websites or apps where SEO
web apps is essential: E-commerce, blogs, news,
marketing websites, etc.
👉 Apps that don’t need SEO
SERVER Empty
Fetch data
🌐 page
CSR
CLIENT Download Render Render app
👩💻 JS bundle spinner with data
SSR
CLIENT Download
Hydrate
👩💻 JS bundle
(
(
(
(
)
)
)
)
SECTION
OVERVIEW OF NEXT.JS WITH THE
"APP" ROUTER
LECTURE
THE MISSING PIECE HYDRATION
:
WHAT IS HYDRATION?
HYDRATION
React component tree
LECTURE
WHAT IS NEXT.JS?
WHAT IS NEXT.JS?
NEXT.JS
👉 Introduced in Next.js 13.4 2023 👉 The first Next.js router since v1 2016
👉 Recommend for new projects 👉 Still supported and updated in the future
👍 Extremely easy to create layouts, loaders, etc. 👎 Data fetching using Next.js-specific APIs such
as getStaticProps and getServerSideProps
👍 More advanced routing (parallel routing, etc.)
LECTURE
WHAT ARE REACT SERVER
COMPONENTS?
WHY REACT SERVER COMPONENTS?
We “hack” this by storing Closer to what a
fetched data in state too real-world app is
UI = f(state) UI = f(data)
UI = f(data, state)
100% 100%
Client-Side Server-side
🧩 The answer is a completely new React paradigm: React Server Components RSC
(
)
WHAT ARE REACT SERVER COMPONENTS?
👉 “Regular” components
👉 A new full-stack architecture for React apps
👉 Created with “use client” directive
👉 Introduces the server as an integral part of at the top of the module
React component trees: server components
CabinRow
Server-client boundary
Split point
between server Duplicate Edit Delete
and client code
CLIENT SERVER
“use client” Default
COMPONENTS COMPONENTS
⚡ State/hooks ✅ YES ❌ NO
📥 Data fetching 🤷 Also possible, preferably with library ✅ Preferred. Use async/away in component
FETCH DATA
Server Components
RE RENDER
🌐 SERVER PROPS
👩💻 CLIENT
DISPLAY DISPLAY
👍 We can compose entire full-stack apps with 👎 Makes React more complex
React components alone (+ server actions 👉)
👎 More things to learn and understand
👍 One single codebase for front and back-end
👎 Things like Context API don’t work in server
👍 Server components have more direct and secure components
access to the data source (no API, no exposing
API keys, etc.) 👎 More decisions to make: “Should this be a
client or a server component?”, “Should I fetch
👍 Eliminate client-server waterfalls by fetching all this data on the server or the client?”, etc.
the data needed for a page at once before
sending it to the client (not each component) 👎 Sometimes you still need to build an API (for
example if you also have a mobile app)
👍 “Disappearing code”: server components ship
no JS, so they can import huge libraries “for free” 👎 Can only be used within a framework
SECTION
OVERVIEW OF NEXT.JS WITH THE
"APP" ROUTER
LECTURE
HOW RSC WORKS BEHIND THE
SCENES
A QUICK REVIEW OF RENDERING IN REACT
“TRADITIONAL” REACT
Components A B C
A
🤔 How does this work in RSC? 👉
Tree of component instances
B B C Component tree)
B A RENDER A
COMMIT TO DOM B D
Server The code from the SERVER CLIENT NOT server and client
component SC SC has disappeared in the typical sense…
render
COMPONENT TREE “VIRTUAL DOM” OF SC TREES OF CC COMPLETE “VIRTUAL DOM”
(RSC PAYLOAD
Client
component CC
The code from the SERVER CLIENT NOT server and client
SC has disappeared in the typical sense…
Merge into existing tree
COMMIT COMMIT
UI = f(data)(state)
DOM Elements DOM Elements
1 2
–
:
+
SECTION
OVERVIEW OF NEXT.JS WITH THE
"APP" ROUTER
LECTURE
RSC VS. SSR HOW ARE THEY
RELATED?
:
REVIEW SERVER SIDE RENDERING SSR
SERVER CLIENT
👋 We’ll be talking about
🌐 👩💻
dynamic SSR HTML
generated at runtime)
RENDER
Interactive
HTML
React App
👉 SSR “Just take this component tree, render it 👉 “Also send the React code to
as HTML, and send that HTML to the browser” make the HTML interactive”
:
(
:
-
(
)
THE RELATIONSHIP BETWEEN RSC AND SSR
SERVER CLIENT
🌐 👩💻 RSC VS. SSR
Doesn’t need to be
👉 RSC is NOT the same as SSR they
an actual web Component tree
are separate technologies
server. Simply of SC and CC
🤔 What
“another computer” about RSC?
RENDER SC
Hydrate 👉 RSC does NOT replace SSR
SERVER CLIENT
🌐 👩💻 RSC VS. SSR
Only client
components 👉 RSC is NOT the same as SSR they
are separate technologies
Component tree Hydrate 👉 RSC does NOT replace SSR
Hydrate
SC and CC D CCs
LOA
PAY 👉 They usually work together:
RSC
RENDER frameworks can combine them
LECTURE
PROJECT PLANNING "THE WILD
OASIS" CUSTOMER WEBSITE
:
THE PROJECT THE WILD OASIS WEBSITE
👉 Guests should be able to learn all about the Wild Oasis Hotel ABOUT
👉 Guests should be able to get information about each cabin and see booked dates
CABINS
👉 Guests should be able to filter cabins by their maximum guest capacity
👉 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) RESERVATIONS
👉 Guests should be able to view all their past and future reservations
👉 Guests need to sign up and log in before they can reserve a cabin and perform any operation
AUTHENTICATION
👉 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
PROFILE
hotel faster
FEATURES PAGES
1⃣ About 1⃣ Homepage /
We’ll use the data and API we already built in the first “Wild Oasis”
👉 DB / API project. If you skipped that project, please go back to the
“Supabase” section to set everything up
LECTURE
WHAT IS REACT SUSPENSE?
WHAT IS REACT SUSPENSE?
App
👉 Built-in React component that we can use to
catch/isolate components (or entire subtrees)
that are not ready to be rendered (“suspending”)
Nav Suspense
👉 What causes a component to be suspending?
List
👉 Native way to support asynchronous operations
in a declarative way (no more isLoading states
Component in Next.js
and render logic 🎉) that will fetch data
(will be suspending)
HOW DOES SUSPENSE WORK?
COMPONENT
While rendering, suspending component is found
TREE
App
These haven’t
been rendered yet
☝ 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.)
(
A LOOK BEHIND THE SCENES
FIBER TREE
Reconciliation App REPRESENTATION
Diffing Another built-in
Child component
Sibling
Nav Suspense Activity = ‘Visible’
‘Hidden’
☝ 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
+
SECTION
DATA FETCHING, CACHING, AND
RENDERING
LECTURE
DIFFERENT TYPES OF SSR STATIC
VS. DYNAMIC RENDERING
:
SERVER SIDE RENDERING IN NEXT.JS
👉 HTML is generated at built time, or 👉 HTML is generated at request time (for each
periodically in the background by re-fetching new request reaches the server)
data ISR, more on this later 👉)
👉 Makes sense if:
👉 Useful when data doesn’t change often and is 1⃣ The data changes frequently and is
not personalized to user (e.g. product page) personalized to the user (e.g. cart)
👉 Default rendering strategy in Next.js (even 2⃣ Rendering a route requires information that
when a page or component fetches data) depends on request (e.g. search params)
Content Delivery
Network
👉 When deployed to Vercel, each static 👉 A route automatically switches to dynamic
route is automatically hosted on a CDN rendering in certain conditions (next slide 👉)
👉 If all routes of an app are static, the entire app 👉 When deployed to Vercel, each dynamic route
can be exported as a static site SSG becomes a serverless function
(
(
)
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:
👉 This is necessary because any of these values can not be known by Next.js at built time
👉 We can also force Next.js to render a route dynamically: These influence caching 34 .
More on this later 👉
👉 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
(
)
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 👉
(
(
)
:
(
)
:
SECTION
DATA FETCHING, CACHING, AND
RENDERING
LECTURE
PARTIAL PRE RENDERING
-
PARTIAL PRE RENDERING PPR A WHOLE NEW WAY OF RENDERING
👋 As of Next.js 14, PPR is highly experimental and should not be used in production
👉 By default, as much as possible of any route will be statically rendered, creating a static shell
👉 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.
👉 Dynamic components or sub-trees are inserted into the static shell as they become available
-
SECTION
DATA FETCHING, CACHING, AND
RENDERING
LECTURE
HOW NEXT.JS CACHES DATA
CACHING IN NEXT.JS
NEXT.JS CACHING
👉 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 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)
👎 Very confusing: Many different Next.js APIs affect and control caching
THE CACHING MECHANISMS
One page Indefinitely, even Until the “Data cache” 30 sec dynamic / 5 min
⏱ How long? request (one across de-deploys (can is invalidated (or app static (throughout one
render, one user) revalidate or opt out) is re-deployed) user session)
🔄 How to revalidate? N.A. 👉 Time-based (automatic) for all data on page: 👉 revalidatePath or
export const revalidate = <time>; (page.js) revalidateTag in SA
👉 Time-based (automatic) for one data request: 👉 router.refresh
Revalidating Data Cache also
fetch('…', { next: { revalidate: <time>} })
revalidates Full Route Cache 👉 cookies.set or
👉 On-demand (manual): cookies.delete in SA
revalidatePath or revalidateTag
LECTURE
BLURRING THE BOUNDARY
BETWEEN SERVER AND CLIENT
THE SERVER CLIENT BOUNDARY FRONT END VS. BACK END
👉 Very clear server-client boundary 👉 No clear separation between front-end and back-end anymore
👉 Communication happens via an API 👉 “Knitting”: pieces of server and client code interweave (composability)
👉 Once JSON arrives from the back-end, 👉 Allow us to build true full-stack applications in just one codebase
the front-end takes over 👉 No need for an intermediary API in many times
[
[
]
:
:
-
-
-
-
-
-
-
-
-
:
[
]
(
)
-
+
:
-
-
IMPORTING VS. RENDERING
Where client-server boundaries are
DEPENDENCY TREE MODULE IMPORTS COMPONENT TREE
A SC A SC
imports renders
B CC D SC C SC B CC C SC
“use client”
“use client” E CC E CC D SC E CC E CC
Client-server boundary “use client”
C CC C CC
📦 Can import Only client components (can’t go back in client-server boundary) Client and server components
✍ Can render Client components and server components passed as props Client and server components
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
(
)
AUTHENTICATION
WITH NEXTAUTH
AUTH.JS
(
)
SECTION
AUTHENTICATION WITH
NEXTAUTH AUTH.JS
LECTURE
WHAT IS MIDDLEWARE IN
NEXT.JS?
(
)
HOW MIDDLEWARE WORKS IN NEXT.JS
2
SEND RESPONSE DIRECTLY USUALLY JSON
👉 Only one middleware function: needs to be exported from 👉 Redirect based on geolocation
middleware.js (or .ts) in the project root folder
👉 A/B testing
👉 Middleware needs to produce a response: 1 or 2
:
:
(
)
MUTATIONS WITH
SERVER ACTIONS
MODERN REACT
HOOKS
+
SECTION
MUTATIONS WITH SERVER
ACTIONS MODERN REACT HOOKS
LECTURE
WHAT ARE SERVER ACTIONS?
+
WHAT ARE SERVER ACTIONS?
That is able to
SERVER ACTIONS handle user input
SERVER SERVER
COMPONENTS ACTIONS
📦 ⚙
-
HOW TO CREATE SERVER ACTIONS
NOT for server components,
SERVER ACTIONS but for server actions
“use server” (“API endpoint”)
👉 The missing piece in the RSC architecture that 1 action attribute in a <form> element (in
enables interactive full-stack applications server and client components)
👉 Async functions that run exclusively on the 2 Event handlers (only client components)
server, allowing us to perform data mutations
3 useEffect (only client components)
👉 Created with the “use server” directive at the
top of the function or an entire module Code is running on the back-end, so
we need to assume inputs are unsafe
👉 Behind the scenes: Next.js creates API endpoint IN SERVER ACTIONS, WE CAN
(with URL for each server action. Whenever a
server action is called, a POST request is made to 👉 Perform data mutations (create, update, delete)
its URL (the function itself never reaches client) 👉 Update the UI with new data: Revalidate cache
with revalidatePath and revalidateTag
👉 Unlike server components, server actions actually
👉 Work with cookies
require a running web server
👉 Many more…
)
:
: