Learning Patterns
Learning Patterns
JS
JS
-
Learning
Patterns
By Lydia Hallie and Addy Osmani
ABOUT
JS
We enable developers to
build amazing things
Authors
Lydia and Addy started work on "Learning Patterns" to bring a modern
perspective to JavaScript design, rendering and performance patterns.
Lydia Hallie
Lydia Hallie is a full-time software engineering consultant
and educator that primarily works with JavaScript, React,
Node, GraphQL, and serverless technologies. She also
spends her time mentoring and doing in-person training
sessions.
Addy Osmani
Addy Osmani is an engineering manager working on
Google Chrome. He leads up teams focused on making the
web fast. Some of the team’s projects include Lighthouse,
PageSpeed Insights, Aurora - working with React/Next.js/
Angular/Vue, contributions to Chrome DevTools and others.
The humans behind patterns.dev
License
DESIGN PATTERNS
Design patterns are a fundamental part of software development, as they
provide typical solutions to commonly recurring problems in software design.
Rather than providing specific pieces of software, design patterns are merely
concepts that can be used to handle recurring themes in an optimized way.
Over the past couple of years, the web development ecosystem has changed
rapidly. Whereas some well-known design patterns may simply not be as
valuable as they used to be, others have evolved to solve modern problems
with the latest technologies.
Facebook's JavaScript library React has gained massive traction in the past 5
years, and is currently the most frequently downloaded framework on
NPM compared to competing JavaScript libraries such
as Angular, Vue, Ember and Svelte. Due to the popularity of React, design
patterns have been modified, optimized, and new ones have been created in
order to provide value in the current modern web development ecosystem.
The latest version of React introduced a new feature called Hooks, which
plays a very important role in your application design and can replace many
traditional design patterns.
Over the years, there has been an increased demand for straight-forward
ways to compose user-interfaces using JavaScript. React, also referred to as
React.js, is an open-source JavaScript library designed by Facebook, used for
building user interfaces or UI components.
When front-end developers talk about code, it's most often in the context of
designing interfaces for the web. And the way we think of interface
composition is in elements, like buttons, lists, navigation, and the likes. React
provides an optimized and simplified way of expressing interfaces in these
elements. It also helps build complex and tricky interfaces by organizing your
interface into three key concepts— components, props, and state.
• Hooks - A new way to use state and other React features without writing
a class
• CRA (Create React App) - A CLI tool to create a scaffolding React app
for bootstrapping a project.
Components are the building blocks of any React app. They are like
JavaScript functions that accept arbitrary input (Props) and return React
elements describing what should be displayed on the screen.
Components let you split your UI into independent, reusable pieces. If you're
used to designing pages, thinking in this modular way might seem like a big
change. But if you use a design system or style guide? Then this might not be
as big of a paradigm shift as it seems.
The most direct way to define a component is to write a JavaScript function.
Extracting components
To illustrate the facts that components can be split into smaller components,
consider the following Tweet component:
Which can be implemented as follows:
The next thing we will do is to a User component that renders an_ Avatar
_next to the user's name:
Extracting components seems like a tedious job, but having reusable
components makes things easier when coding for larger apps. A good
criterion to consider when simplifying components is this: if a part of your UI is
used several times (Button, Panel, Avatar), or is complex enough on its own
(App, FeedStory, Comment), it is a good candidate to be extracted to a
separate component.
Props
Props are a short form for properties, and they simply refer to the internal data
of a component in React. They are written inside component calls and are
passed into components. They also use the same syntax as HTML attributes,
e.g._ prop="value". Two things that are worth remembering about props;
Firstly, we determine the value of a prop and use it as part of the blueprint
before the component is built. Secondly, the value of a prop will never change,
i.e. props are read-only once they are passed into components.
The way you access a prop is by referencing it via the "this.props" property
that every component has access to.
State
State is an object that holds some information that may change over the
In React, state can also be tracked globally, and data can be shared between
components as needed. Essentially, this means that in React apps, loading
data in new places is not as expensive as it is with other technologies. React
apps are smarter about which data they save and load, and when. This opens
up opportunities to make interfaces that use data in new ways.
Think of React components like micro-applications with their own data, logic,
and presentation. Each component should have a single purpose. As an
engineer, you get to decide that purpose and have complete control over how
each component behaves and what data is used. You're no longer limited by
the data on the rest of the page. In your design, you can take advantage of
this in all kinds of ways. There are opportunities to present additional data that
can improve the user experience or make areas within the design more
contextual.
Props vs State
Props and state can sometimes be confused with each other because of how
similar they are. Here are some key differences between them:
Props State
The data remains
component unchanged from Data is the current snapshot of data stored in a component's
to component.
Props. It changes over the lifecycle of the component.
The data in props cannot be The data in state can be modified using this.setState
modified
Lifecycle
Every react component goes through three stages; mounting, rendering, and
dismounting. The series of events that occur during these three stages can be
referred to as the component's lifecycle. While these events are partially
related to the component's state (its internal data), the lifecycle is a bit
different. React has internal code that loads and unloads components as
needed, and a component can exist in several stages of use within that
internal code.
There are a lot of lifecycle methods, but the most common ones are:
render() This method is the only required method within a class component
in React and is the most used. As the name suggests, it handles the rendering
of your component to the UI, and it happens during the mounting and
rendering of your component.
Context
In a typical React app, data is passed down via props, but this can be
cumbersome for some types of props that are required by many components
within an application. Context provides a way to share these types of data
between components without having to explicitly pass a prop through every
level of hierarchy. Meaning with context, we can avoid passing props through
intermediate elements.
React Hooks
Hooks are functions that let you "hook into" React state and lifecycle features
from functional components. They let you use state and other React features
without writing a class. You can learn more about Hooks in our Hooks guide.
Thinking in React
One thing that is really amazing about React is how it makes you think about
apps as you build them. In this section, we'll walk you through the thought
process of building a Searchable product data table using React Hooks.
Step 1: Start with a Mock
Imagine that we already have a JSON API and a mock of our interface:
Our JSON API returns some data that looks like this:
Tip: You may find free tools like Excalidraw useful for drawing out a high-level
When you have your mock, the next thing to do is to draw boxes around every
component (and subcomponent) in the mock and name all of them, as shown
below.
You'll see in the image above that we have five components in our app. We've
listed the data each component represents.
• TweetSearchResults (orange): container for the full component
Now that the components in the mock have been identified, the next thing to
do would be to sort them into a hierarchy. Components that are found within
another component in the mock should appear as a child in the hierarchy. Like
this:
• TweetSearchResults
• SearchBar
• TweetList
• TweetCategory
• TweetRow
Tweet Row
The final implementation would be all the code written together in the
previously stated hierarchy :
• TweetSearchResults
• SearchBar
• TweetList
• TweetCategory
• TweetRow
Getting Started
There are various ways to start using React.
Load directly on the web page: This is the simplest way to set up React.
Add the React JavaScript to your page, either as an npm dependency or via
a CDN.
This guide would not have been possible without the teaching styles shared in
the official React components and props, thinking in React, thinking in React
Hooks and the scriptverse docs
Share a single global instance throughout our application
Singletons are classes which can be instantiated once, and can be accessed
globally. This single instance can be shared throughout our application, which
makes Singletons great for managing global state in an application.
First, let's take a look at what a singleton can look like using an ES2015 class.
For this example, we’re going to build a Counter class that has:
a getInstance method that returns the value of the instance
a getCount method that returns the current value of the counter variable
However, this class doesn’t meet the criteria for a Singleton! A Singleton
should only be able to get instantiated once. Currently, we can create multiple
instances of the Counter class.
By calling the new method twice, we just set counter1 and counter2 equal
to different instances. The values returned by the getInstance method
on counter1 and counter2 effectively returned references to different
instances: they aren't strictly equal!
Let’s make sure that only one instance of the Counter class can be created.
One way to make sure that only one instance can be created, is by creating a
variable called instance. In the constructor of Counter, we can
set instance equal to a reference to the instance when a new instance is
created. We can prevent new instantiations by checking if
the instance variable already had a value. If that's the case, an instance
already exists. This shouldn't happen: an error should get thrown.
Perfect! We aren't able to create multiple instances anymore.
Let's export the Counter instance from the counter.js file. But before
doing so, we should freeze the instance as well.
The Object.freeze method makes sure that consuming code cannot
modify the Singleton. Properties on the frozen instance cannot be added or
modified, which reduces the risk of accidentally overwriting the values on the
Singleton.
Let's take a look at an application that implements the Counter example. We
have the following files:
different files.
(Dis)advantages
Restricting the instantiation to just one instance could potentially save a lot of
memory space. Instead of having to set up memory for a new instance each
time, we only have to set up memory for that one instance, which is
Let's use the same example as we saw previously. However this time,
the counter is simply an object containing:
• a count property
Testing code that relies on a Singleton can get tricky. Since we can't create
new instances each time, all tests rely on the modification to the global
instance of the previous test. The order of the tests matter in this case, and
one small modification can lead to an entire test suite failing. After testing, we
need to reset the entire instance in order to reset the modifications made by
the tests.
Dependency hiding
When importing another module, superCounter.js in this case, it may not be
obvious that that module is importing a Singleton. In other files, such
as index.js in this case, we may be importing that module and invoke its
methods. This way, we accidentally modify the values in the Singleton. This
can lead to unexpected behavior, since multiple instances of the Singleton can
be shared throughout the application, which would all get modified as well.
index.js
Global behavior
However, the common usecase for a Singleton is to have some sort of global
state throughout your application. Having multiple parts of your codebase rely
on the same mutable object can lead to unexpected behavior.
Usually, certain parts of the codebase modify the values within the global
state, whereas others consume that data. The order of execution here is
important: we don't want to accidentally consume data first, when there is no
data to consume (yet)! Understanding the data flow when using a global state
can get very tricky as your application grows, and dozens of components rely
on each other.
In React, we often rely on a global state through state management tools such
as Redux or React Context instead of using Singletons. Although their global
state behavior might seem similar to that of a Singleton, these tools provide
a read-only state rather than the mutable state of the Singleton. When using
Redux, only pure function reducers can update the state, after a component
has sent an action through a dispatcher.
With a Proxy object, we get more control over the interactions with certain
objects. A proxy object can determine the behavior whenever we're interacting
with the object, for example when we're getting a value, or setting a value.
Instead of interacting with this object directly, we want to interact with a proxy
object. In JavaScript, we can easily create a new proxy with by creating a new
instance of Proxy.
The second argument of Proxy is an object that represents the handler. In
the handler object, we can define specific behavior based on the type of
interaction. Although there are many methods that you can add to the Proxy
handler, the two most common ones are get and set:
The proxy makes sure that we weren't modifying the person object with faulty
values, which helps us keep our data pure!
Reflect
JavaScript provides a built-in object called Reflect, which makes it easier
for us to manipulate the target object when working with proxies.
Previously, we tried to modify and access properties on the target object within
the proxy through directly getting or setting the values with bracket notation.
Instead, we can use the Reflect object. The methods on
the Reflect object have the same name as the methods on
the handler object.
Perfect! We can access and modify the properties on the target object easily
with the Reflect object.
Proxies are a powerful way to add control over the behavior of an object. A
proxy can have various use-cases: it can help with validation, formatting,
notifications, or debugging.
each handler method invocation can easily affect the performance of your
application negatively. It's best to not use proxies for performance-critical
code.
Make data available to multiple child components
In some cases, we want to make available data to many (if not all)
components in an application. Although we can pass data to components
using props, this can be difficult to do if almost all components in your
We often end up with something called prop drilling, which is the case when
we pass props far down the component tree. Refactoring the code that relies
on the props becomes almost impossible, and knowing where certain data
comes from is difficult.
Let's say that we have one App component that contains certain data. Far
down the component tree, we have a ListItem, Header and
Text component that all need this data. In order to get this data to these
components, we'd have to pass it through multiple layers of components.
In our codebase, that would look something like the following:
Passing props down this way can get quite messy. If we want to rename
the data prop in the future, we'd have to rename it in all components. The
bigger your application gets, the trickier prop drilling can be.
It would be optimal of we could skip all the layers of components that don't
need to use this data. We need to have something that gives the components
that need access to the value of data direct access to it, without relying on
prop drilling.
This is where the Provider Pattern can help us out! With the Provider Pattern,
we can make data available to multiple components. Rather than passing that
data down each layer through props, we can wrap all components in
The Provider receives a value prop, which contains the data that we want to
pass down. All components that are wrapped within this provider have access
to the value of the value prop.
We no longer have to manually pass down the data prop to each component!
Each component can get access to the data, by using the useContext hook.
This hook receives the context that data has a reference with, DataContext
in this case. The useContext hook lets us read and write data to the context
object.
The components that aren't using the data value won't have to deal
with data at all. We no longer have to worry about passing props down several
levels through components that don't need the value of the props, which
makes refactoring a lot easier.
The Provider pattern is very useful for sharing global data. A common use
case for the provider pattern is sharing a theme UI state with many
components.
Say we have a simple app that shows a list.
App.js
List.js
We want the user to be able to switch between light mode and dark mode, by
toggling the switch. When the user switches from dark- to light mode and vice
versa, the background color and text color should change! Instead of passing
the current theme value down to each component, we can wrap the
components in a ThemeProvider, and pass the current theme colors to the
provider.
Since the Toggle and List components are both wrapped within
the ThemeContext provider, we have access to the
values theme and toggleTheme that are passed as a value to the provider.
The List component itself doesn't care about the current value of the theme.
However, the ListItem components do! We can use the theme context
directly within the ListItem.
Perfect! We didn't have to pass down any data to components that didn't care
about the current value of the theme.
Hooks
provider.
Each component that needs to have access to the ThemeContext, can now
simply use the useThemeContext hook.
export default function ListItem ( ) {
const theme useThemeContext ( ) ;
=
The prototype pattern is a useful way to share properties among many objects
of the same type. The prototype is an object that's native to JavaScript, and
can be accessed by objects through the prototype chain.
In our applications, we often have to create many objects of the same type. A
useful way of doing this is by creating multiple instances of an ES6 class.
Let's say we want to create many dogs! In our example, dogs can't do that
much: they simply have a name, and they can bark!
Notice here how the constructor contains a name property, and the class itself
contains a bark property. When using ES6 classes, all properties that are
defined on the class itself, bark in this case, are automatically added to
the prototype.
We can see the prototype directly through accessing the prototype property
on a constructor, or through the__proto__ property on any instance.
Since all instances have access to the prototype, it's easy to add properties to
the prototype even after creating the instances.
Say that our dogs shouldn't only be able to bark, but they should also be able
to play! We can make this possible by adding a play property to the prototype.
The term prototype chain indicates that there could be more than one step.
Indeed! So far, we've only seen how we can access properties that are directly
available on the first object that__proto__ has a reference to. However,
prototypes themselves also have a __proto__ object!
Let's create another type of dog, a super dog! This dog should inherit
everything from a normal Dog, but it should also be able to fly. We can create
a super dog by extending the Dog class and adding a fly method.
Let's create a flying dog called Daisy, and let her bark and fly!
We have access to the bark method, as we extended the Dog class. The
value of __proto__ on the prototype of SuperDog points to
the Dog.prototype object!
It gets clear why it's called a prototype chain: when we try to access a
property that's not directly available on the object, JavaScript recursively
walks down all the objects that __proto__ points to, until it finds the
property!
Object.create
The Object.create method lets us create a new object, to which we can
explicitly pass the value of its prototype.
Although pet1 itself doesn't have any properties, it does have access to
properties on its prototype chain! Since we passed the dog object as pet1’s
prototype, we can access the bark property.
Perfect! Object.create is a simple way to let objects directly inherit
properties from other objects, by specifying the newly created object's
prototype. The new object can access the new properties by walking down the
prototype chain.
The prototype pattern allows us to easily let objects access and inherit
properties from other objects. Since the prototype chain allows us to access
properties that aren't directly defined on the object itself, we can avoid
Let's say we want to create an application that fetches 6 dog images, and
renders these images on the screen. Ideally, we want to enforce separation of
concerns by separating this process into two parts:
Let's take a look at the example that displays the dog images. When rendering
the dog images, we simply want to map over each dog image that was
fetched from the API, and render those images. In order to do so, we can
create a functional component that receives the data through props, and
renders the data it received.
DogImages.js
Container Components
The primary function of container components is to pass data to
presentational components, which they contain. Container components
themselves usually don't render any other components besides the
presentational components that care about their data. Since they don't render
anything themselves, they usually do not contain any styling either.
return dogs.map ( ( dog , i ) => < img src ={ dog } key={ i } alt = " Dog " / > ) ;
}
useEffect ( ( . => {
async function fetchDogs ( ) {
const res = await fetch (
fetchdogs ( ) ;
}, [] );
return dogs ;
}
By using the useDogImages hook, we still separated the application logic
from the view. We're simply using the returned data from
the useDogImages hook, without modifying that data within
the DogImages component.
Hooks make it easy to separate logic and view in a component, just like the
Container/Presentational pattern. It saves us the extra layer that was
necessary in order to wrap the presentational component within the container
component.
Pros
There are many benefits to using the Container/Presentational pattern.
With the observer pattern, we can subscribe certain objects, the observers, to
another object, called the observable. Whenever an event occurs, the
observable notifies all its observers!
Awesome! We can now add observers to the list of observers with the
subscribe method, remove the observers with the unsubscribe method, and
notify all subscribes with the notify method.
Let’s build something with this observable. We have a very basic app that only
consists of two components: a Button, and a Switch.
We want to keep track of the user interaction with the application. Whenever a
user either clicks the button or toggles the switch, we want to log this event
with the timestamp. Besides logging it, we also want to create a toast
notification that shows up whenever an event occurs!
First, let's create the logger and tastily functions. These functions will
eventually receive data from the notify method.
Currently, the logger and toastify functions are unaware of observable:
the observable can't notify them yet! In order to make them observers, we’d
have to subscribe them, using the subscribe method on the observable!
Whenever an event occurs, the logger and toastify functions will get
notified. Now we just need to implement the functions that actually notify the
observable: the handleClick and handleToggle functions! These functions
should invoke the notify method on the observable, and pass the data that the
observers should receive.
import { ToastContainer , toast } from " react - toastify " ;
observable.subscribe ( logger ) ;
observable . subscribe (toastify ) ;
return (
<div className= " App " >
< Button > Click me ! < / Button >
< FormControlLabel control = { < Switch / > } / >
<ToastContainer / >
</ div>
);
}
invoke
Awesome! We just
the notify method theentire
on the
finished flow:with
observer the data,and
handleClick which the
afterhandleToggle
observer notifies the subscribers: the logger and toastify functions in this
case.
Whenever a user interacts with either of the components, both the logger and
the toastify functions will get notified with the data that we passed to
the notify method!
Observable.js
App.js
function handleClick ( ) {
observable.notify ( " User clicked button ! " ) ;
}
function handleToggle ( ) {
observable.notify ( " User toggled switch ! " ) ;
}
});
}
Pros
Using the observer pattern is a great way to enforce separation of
concerns and the single-responsiblity principle. The observer objects aren’t
tightly coupled to the observable object, and can be (de)coupled at any time.
The observable object is responsible for monitoring the events, while the
observers simply handle the received data.
Cons
If an observer becomes too complex, it may cause performance issues when
notifying all subscribers.
Case study
A popular library that uses the observable pattern is RxJS.
ReactiveX combines the Observer pattern with the Iterator pattern and
functional programming with collections to fill the need for an ideal way of
managing sequences of events. - RxJS
With RxJS, we can create observables and subscribe to certain events! Let’s
look at an example that’s covered in their documentation, which logs whether
Besides being able to split your code into smaller reusable pieces, modules
allow you to keep certain values within your file private. Declarations within a
module are scoped (encapsulated) to that module , by default. If we don’t
explicitly export a certain value, that value is not available outside that
module. This reduces the risk of name collisions for values declared in other
parts of your codebase, since the values are not available on the global
scope.
ES2015 Modules
ES2015 introduced built-in JavaScript modules. A module is a file containing
JavaScript code, with some difference in behavior compared to a normal
script.
Let's look at an example of a module called math.js, containing
mathematical functions.
math.js
However, we don’t just want to use these functions in the math.js file, we
want to be able to reference them in the index.js file!
In order to make the functions from math.js available to other files, we first
have to export them. In order to export code from a module, we can use
the export keyword.
One way of exporting the functions, is by using named exports: we can simply
add the export keyword in front of the parts that we want to publicly expose.
In this case, we’ll want to add the export keyword in front of every function,
since index.js should have access to all four functions.
math.js
index.js
The reference error is gone, we can now use the exported values from the
module!
A great benefit of having modules, is that we only have access to the values
that we explicitly exported using the export keyword. Values that we didn't
explicitly export using the export keyword, are only available within that
module.
Let's create a value that should only be referenceable within the math.js file,
called privateValue.
math.js
Notice how we didn't add the export keyword in front of privateValue. Since we
didn’t export the privateValue variable, we don’t have access to this value
outside of the math.js module!
Sometimes, the names of the exports could collide with local values.
index.js
Besides named exports, which are exports defined with just
the export keyword, you can also use a default export. You can only
have one default export per module.
Let’s make the add function our default export, and keep the other functions
as named exports. We can export a default value, by adding export
default in front of the value.
math.js
The difference between named exports and default exports, is the way the
value is exported from the module, effectively changing the way we have to
import the value.
index.js
The value that's been imported from a module without the brackets, is always
the value of the default export, if there is a default export available.
Since JavaScript knows that this value is always the value that was exported
by default, we can give the imported default value another name than the
name we exported it with. Instead of importing the add function using the
name add, we can call it addValues, for example.
index.js
Even though we exported the function called add, we can import it calling it
anything we like, since JavaScript knows you are importing the default export.
We can also import all exports from a module, meaning all named
exports and the default export, by using an asterisk * and giving the name we
want to import the module as. The value of the import is equal to an object
containing all the imported values.
index.js
In this case, we're importing all exports from a module. Be careful when doing
this, since you may end up unnecessarily importing values. Using the * only
imports all exported values. Values private to the module are still not available
in the file that imports the module, unless you explicitly exported them.
React
When building applications with React, you often have to deal with a large
amount of components. Instead of writing all of these components in one file,
we can separate the components in their own files, essentially creating a
module for each component.
We have a basic todo-list, containing a list, list items, an input field, and
a button.
App.js
Button.js
Input.js
Throughout the app, we don't want to use the default Button and
Input component, imported from the material-ui library. Instead, we want to
use our custom version of the components, by adding custom styles to it
defined in the styles object in their files.
Rather than importing the default Button and Input component each time in
our application and adding custom styles to it over and over, we can now
simply import the default Button and Input component once, add styles,
and export our custom component.
Dynamic import
When importing all modules on the top of a file, all modules get loaded before
the rest of the file. In some cases, we only need to import a module based on
We only have to load, parse, and compile the code that the user really
needs, when the user needs it.
With the module pattern, we can encapsulate parts of our code that should not
be publicly exposed. This prevents accidental name collision and global scope
pollution, which makes working with multiple dependencies and namespaces
less risky. In order to be able to use ES2015 modules in all JavaScript
runtimes, a transpiler such as Babel is needed.
Add functionality to objects or classes without inheritance
inheritance.
Let's say that for our application, we need to create multiple dogs. However,
the basic dog that we create doesn't have any properties but a name property.
A dog should be able to do more than just have a name. It should be able to
bark, wag its tail, and play! Instead of adding this directly to the Dog, we can
create a mixin that provides the bark, wagTail and play property for us.
We can add the dogFunctionality mixin to the Dog prototype with
the Object.assign method. This method lets us add properties to the target
object: Dog.prototype in this case. Each new instance of Dog will have
access to the the properties of dogFunctionality, as they're added to
the Dog's prototype!
Let's create our first pet, pet1, called Daisy. As we just added
the dogFunctionality mixin to the Dog's prototype, Daisy should be able
to walk, wag her tail, and play!
Most mammals (besides dolphins.. and maybe some more) can walk and
sleep as well. A dog is a mammal, and should be able to walk and sleep!
Let's create a animalFunctionality mixin that adds
the walk and sleep properties.
We can add these properties to the dogFunctionality prototype,
using Object.assign. In this case, the target object
is dogFunctionality.
Perfect! Any new instance of Dog can now access the walk and
sleep methods as well.
class Dog {
constructor ( name ) {
this.name = name ;
}
}
const animalfunctionality = {
walk : ( ). => console.log ( "Walking ! " ) ,
sleep : ( ) => console.log ( " Sleeping ! " )
};
=
const dogFunctionality {
__proto__ : animalfunctionality ,
bark : ( => console.log ( "Woof ! " ) ,
wagTail : ( ) => console.log ( "Wagging my tail ! " ) ,
play : ( ) => console.log ( " Playing ! " ) ,
walk ( ) {
super.walk ( ) ;
},
sleep ( ) {
super.sleep ( ) ;
}
};
console.log ( pet1.name ) ;
peti.bark ( ) ;
pet1.play ( ) ;
pet1.walk ( ) ;
peti.sleep ( ) ;
An example of a mixin in the real world is visible on the Window interface in a
browser environment. The Window object implements many of its properties
from the WindowOrWorkerGlobalScope and WindowEventHandlers
mixins, which allow us to have access to properties such as setTimeout
and setInterval, indexedDB, and isSecureContext.
Since it's a mixin, thus is only used to add functionality to objects, you won't
be able to create objects of type WindowOrWorkerGlobalScope.
React (pre ES6)
Mixins were often used to add functionality to React components before the
introduction of ES6 classes. The React team discourages the use of mixins as
it easily adds unnecessary complexity to a component, making it hard to
maintain and reuse. The React team encouraged the use of higher order
components instead, which can now often be replaced by Hooks.
The mediator pattern makes it possible for components to interact with each
other through a central point: the mediator. Instead of directly talking to each
other, the mediator receives the requests, and sends them forward! In
JavaScript, the mediator is often nothing more than an object literal or a
function.
You can compare this pattern to the relationship between an air traffic
controller and a pilot. Instead of having the pilots talk to each other directly,
which would probably end up being quite chaotic, the pilots talk the air traffic
controller. The air traffic controller makes sure that all planes receive the
information they need in order to fly safely, without hitting the other airplanes.
We can create new users that are connected to the chat room. Each user
instance has a send method which we can use in order to send messages.
class ChatRoom {
logMessage ( user , message ) {
const sender = user.getName ( ) ;
console.log ( ^ ${ new Date ( ) . toLocaleString ( ) } [ ${ sender } ] : ${message } " ) ;
}
}
class User {
constructor ( name , chatroom ) {
this.name = name ;
this.chatroom =
chatroom ;
}
getName ( ) {
return this.name ;
}
send ( message ) {
this.chatroom.logMessage ( this , message ) ;
}
}
Say we want add a header to the request if the user hits the root /. We can
add this header in a middleware callback.
The next method calls the next callback in the request-response cycle. We'd
effectively be creating a chain of middleware functions that sit between the
request and the response, or vice versa.
Let's add another middleware function that checks whether the test
header was added correctly. The change added by the previous middleware
Perfect! We can track and modify the request object all the way to the
response through one or multiple middleware functions.
Every time the user hits a root endpoint '/', the two middleware
callbacks will be invoked.
In the section on Higher Order Components, we saw that being able to reuse
component logic can be very convenient if multiple components need access
to the same data, or contain the same logic.
We can use a render prop for this! Let's pass the value that we want
the Title component to render to the render prop.
Within the Title component, we can render this data by returning the
invoked render prop!
To the Title element, we have to pass a prop called render, which is a
function that returns a React element.
Perfect, works smoothly! The cool thing about render props, is that the
component that receives the prop is very reusable. We can use it multiple
times, passing different values to the render prop each time.
Although they're called render props, a render prop doesn't have to be
called render. Any prop that renders JSX is considered a render prop! Let's
rename the render props that were used in the previous example, and give
them specific names instead!
Great! We've just seen that we can use render props in order to
make a component reusable, as we can pass different data to the render
prop each time. But, why would you want to use this?
A component that takes a render prop usually does a lot more than simply
invoking the render prop. Instead, we usually want to pass data from the
component that takes the render prop, to the element that we pass as a
render prop!
The render prop can now receive this value that we passed as its argument.
Let's look at an example! We have a simple app, where a user can type a
function Input ( ) {
const [ value , setValue ] = useState ( " " ) ;
return (
< input
type = " text "
value ={ value }
onChange = { e => setValue ( e.target.value ) }
placeholder = " Temp in ° C "
17
);
}
Lifting state
One way to make the users input available to both
the Fahrenheit and Kelvin component in the above example, we'd have
to lift the state
Instead, we can use render props! Let's change the Input component in a way
that it can receive render props
Perfect, the Kelvin and Fahrenheit components now have access to the
value of the user's input!
One way to use Apollo Client is through the Mutation and Query
components. Let's look at the same Input example that was covered in the
Higher Order Components section. Instead of using a the graphql() higher
order component, we’ll now use the Mutation component that receives a
render prop.
import React from " react " ;
import " ./styles.css " ;
handleChange =
( e ) => {
this.setState ( { message : e.target.value } ) ;
};
render ( ) {
return (
<Mutation
mutation ={ ADD_MESSAGE }
variables={ { message : this.state.message } }
onCompleted={ ( ) =>
console.log ( ` Added with render prop : $ { this.state.message } ^ )
}
{ ( addMessage ) => (
< div className = " input - row " >
< input
onChange={ this.handleChange }
type= " text"
placeholder = " Type something..."
/>
< button onclick={ addMessage }>Add < / button >
< / div>
)}
< / Mutation >
);
}
}
In order to pass data down from the Mutation component to the elements
that need the data, we pass a function as a child. The function receives the
value of the data through its arguments.
Although we can still use the render prop pattern and is often preferred
compared to the higher order component pattern, it has its downsides.
Let's look at an example that uses the exact same data as we previously saw
in the example with the Query render prop. This time, we'll provide the data to
the component by using the useQuery hook that Apollo Client provided for
us.
By using the useQuery hook, we reduced the amount of code that was
needed in order to provide the data to the component.
Pros
Sharing logic and data among several components is easy with the render
props pattern. Components can be made very reusable, by using a render
or children prop. Although the Higher Order Component pattern mainly solves
the same issues, namely reusability and sharing data, the render props
pattern solves some of the issues we could encounter by using the HOC
pattern.
The issue of naming collisions that we can run into by using the HOC pattern
no longer applies by using the render props pattern, since we don't
automatically merge props. We explicitly pass the props down to the child
components, with the value provided by the parent component.
Since we explicitly pass props, we solve the HOC's implicit props issue. The
props that should get passed down to the element, are all visible in the render
prop's arguments list. This way, we know exactly where certain props come
from.
We can separate our app's logic from rendering components through render
props. The stateful component that receives a render prop can pass the data
onto stateless components, which merely render the data.
Cons
The issues that we tried to solve with render props, have largely been
replaced by React Hooks. As Hooks changed the way we can add reusability
and data sharing to components, they can replace the render props pattern in
many cases.
Since we can't add lifecycle methods to a render prop, we can only use it on
components that don't need to alter the data they receive.
Use functions to reuse stateful logic among multiple components
throughout the app
React 16.8 introduced a new feature called Hooks. Hooks make it possible to
use React state and lifecycle methods, without having to use a ES2015 class
component.
Although Hooks are not necessarily a design pattern, Hooks play a very
important role in your application design. Many traditional design patterns can
be replaced by Hooks.
Class components
Before Hooks were introduced in React, we had to use class components in
order to add state and lifecycle methods to components. A typical class
component in React can look something like:
A class component can contain a state in its constructor, lifecycle methods
such as componentDidMount and componentWillUnmount to perform
side effects based on a component's lifecycle, and custom methods to add
Although we can still use class components after the introduction of React
Hooks, using class components can have some downsides! Let's look at
some of the most common issues when using class components.
Understanding ES2015 classes
Since class components were the only component that could handle state and
Besides having to make sure you don't accidentally change any behavior
while refactoring the component, you also need to understand how ES2015
classes work. Why do we have to bind the custom methods? What does
the constructor do? Where does the this keyword come from? It can be
difficult to know how to refactor a component properly without accidentally
changing the data flow.
Restructuring
The common way to share code among several components, is by using
the Higher Order Component or Render Props pattern. Although both patterns
are valid and a good practice, adding those patterns at a later point in time
requires you to restructure your application.
Besides having to restructure your app, which is trickier the bigger your
components are, having many wrapping components in order to share code
among deeper nested components can lead to something that's best referred
to as a wrapper hell. It's not uncommon to open your dev tools and seeing a
structure similar to:
The wrapper hell can make it difficult to understand how data is flowing
through your application, which can make it harder to figure out why
Complexity
Lifecycle methods also require quite a lot of duplication in the code. Let's take
a look at an example, which uses a Counter component and
a Width component.
componentDidMount ( ) {
this.handleResize ( ) ;
window.addEventListener ( " resize " , this.handleResize ) ;
}
componentWillunmount ( ) {
window.removeEventListener ( " resize " , this.handleResize ) ;
}
increment = ( ) => {
this.setState ( ( { count } ) => ( { count : count + 1 } ) ) ;
};
decrement = ( ) => { =
handleResize = ( ) => {
this.setState ( { width : window.innerWidth } ) ;
};
render ( ) {
return (
<div className = " App " >
< Count
count ={ this.state.count }
increment ={ this.increment }
decrement ={ this.decrement }
/>
< div id = " divider " / >
<Width width={ this.state.width } / >
</ div >
);
}
}
The way the App component is structured can be visualized as the following:
Although this is a small component, the logic within the component is already
quite tangled. Whereas certain parts are specific for the counter logic, other
parts are specific for the width logic. As your component grows, it can get
increasingly difficult to structure logic within your component, find related logic
within the component.
Besides tangled logic, we're also duplicating some logic within the lifecycle
functions that you can use to manage a components state and lifecycle
methods. React Hooks make it possible to:
• reuse the same stateful logic among multiple components throughout the
app
First, let's take a look at how we can add state to a functional component,
using React Hooks.
State Hook
React provides a hook that manages state within a functional component,
called useState.
Since we're dealing with the value of an input, let's call the current value of the
state input, and the method in order to update the state setInput. The initial
value should be an empty string.
We can now refactor the Input class component into a stateful functional
component.
The value of the input field is equal to the current value of the input state, just
like in the class component example. When the user types in the input field,
the value of the input state updates accordingly, using the setInput method.
Effect Hook
We've seen we can use the useState component to handle state within a
functional component, but another benefit of class components was the
possibility to add lifecycle methods to a component.
Let's use the input example we used in the State Hook section. Whenever the
user is typing anything in the input field, we also want to log that value to the
console.
We need to use a useEffect hook that "listens" to the input value. We can
do so, by adding input to the dependency array of the useEffect hook. The
dependency array is the second argument that the useEffect hook
receives.
The value of the input now gets logged to the console whenever the user
types a value.
Custom Hooks
You may have noticed that all hooks start with use. It's important to start your
hooks with use in order for React to check if it violates the rules of Hooks.
Let's say we want to keep track of certain keys the user may press when
writing the input. Our custom hook should be able to receive the key we want
to target as its argument.
We want to add a keydown and keyup event listener to the key that the user
passed as an argument. If the user pressed that key, meaning
the keydown event gets triggered, the state within the hook should toggle
to true. Else, when the user stops pressing that button, the keyup event gets
triggered and the state toggles to false.
function useKeyPress ( targetKey ) {
const [ keyPressed , setKeyPressed ] React.useState ( false ) ;
React.useEffect ( ( ) => {
window.addEventListener ( " keydown " , handleDown ) ;
window.addEventListener ( " keyup " , handleUp ) ;
return ( ) => {
window.removeEventListener ( " keydown " , handleDown ) ;
window.removeEventListener ( "keyup " , handleUp ) ;
};
}, [] );
return keyPressed ;
}
Perfect! We can use this custom hook in our input application. Let's log to the
console whenever the user presses the q, l or w key.
Instead of keeping the key press logic local to the Input component, we can
now reuse the useKeyPress hook throughout multiple components, without
having to rewrite the same logic over and over.
Another great advantage of Hooks, is that the community can build and share
hooks. We just wrote the useKeyPress hook ourselves, but that actually
wasn't necessary at all! The hook was already built by someone else and
ready to use in our application if we just installed it!
Let's rewrite the counter and width example shown in the previous section.
Instead of using a class component, we'll rewrite the app using React Hooks.
import React , { useState , useEffect } from " react " ;
import " ./styles.css " ;
function useCounter ( ) {
const [ count , setCount ] = useState ( 0 ) ;
const increment =
( ) => setCount ( count + 1 ) ;
const decrement =
( ) = > setCount ( count - 1 ) ;
function useWindowWidth ( ) {
const [ width , setWidth ] =
useState ( window.innerWidth ) ;
useEffect ( ( ). = > {
=
const handleResize = ( ) == >> setWidth (window .innerWidth ) ;
window.addEventListener ( " resize " , handleResize ) ;
return ( ) => window.addEventListener ( " resize" , handleResize ) ;
});
return width ;
}
return (
<div className= " App " >
< Count
count ={ counter.count }
increment={ counter.increment }
decrement ={ counter.decrement }
/>
< div id = " divider " / >
<Width width ={ width } / >
< / div >
);
}
We broke the logic of the App function into several pieces:
Let's visualize the changes we just made, compared to the old App class
component.
Using React Hooks just made it much clearer to separate the logic of our
component into several smaller pieces. Reusing the same stateful logic just
became much easier, and we no longer have to rewrite functional components
into class components if we want to make the component stateful. A good
knowledge of ES2015 classes is no longer required, and having reusable
stateful logic increases the testability, flexibility and readability of components.
Adding Hooks
Like other components, there are special functions that are used when you
want to add Hooks to the code you have written. Here's a brief overview of
some common Hook functions:
useState
useEffect
The useEffect Hook is used to run code during major lifecycle events in a
function component. The main body of a function component does not allow
mutations, subscriptions, timers, logging, and other side effects. If they are
allowed, it could lead to confusing bugs and inconsistencies within the UI. The
useEffect hook prevents all of these "side effects" and allows the UI to run
smoothly. It is a combination
of componentDidMount , componentDidUpdate ,
and componentWillUnmount, all in one place.
useContext
The useContext Hook accepts a context object, which is the value returned
from React.createContext, and returns the current context value for that
context. The useContext Hook also works with the React Context API in order
to share data throughout the app without the need to pass your app props
down through various levels.
It should be noted that the argument passed to the useContext hook must
be the context object itself and any component calling
the useContext always re-render whenever the context value changes.
useReducer
a reducer function and an initial state input and returns the current state and
a dispatch function as output by means of array
destructuring. useReducer also optimizes the performance of components
that trigger deep updates.
Pros and Cons of using Hooks
Fewer lines of code Hooks allows you group code by concern and
functionality, and not by lifecycle. This makes the code not only cleaner and
concise but also shorter. Below is a comparison of a simple stateless
component of a searchable product data table using React, and how it looks
in Hooks after using the useState keyword.
Stateless Component
Same component with Hooks
JavaScript classes can be difficult to manage, hard to use with hot reloading
and may not minify as well. React Hooks solves these problems and ensures
• Have to respect its rules, without a linter plugin, it is difficult to know which
rule has been broken.
Here are some differences between Hooks and Classes to help you decide:
It provides uniformity across Classes confuse both humans and machines due to the need to
React components. understand binding and the context in which functions are called.
Pass reusable logic down as props to components throughout your
application
Within our application, we often want to use the same logic in multiple
components. This logic can include applying a certain styling to components,
requiring authorization, or adding a global state.
One way of being able to reuse the same logic in multiple components, is by
using the higher order component pattern. This pattern allows us to reuse
component logic throughout our application.
Let’s take a look at the same DogImages example that was previously used
in the Container/Presentational pattern! The application does nothing more
than rendering a list of dog images, fetched from an API.
Let's improve the user experience a little bit. When we’re fetching the data, we
want to show a Loading… screen to the user. Instead of adding data to
the DogImages component directly, we can use a Higher Order Component
that adds this logic for us.
To make the withLoader HOC very reusable, we won't hardcode the Dog
API url in that component. Instead, we can pass the URL as an argument to
the withLoader HOC, so this loader can be used on any component that
needs a loading indicator while fetching data from a different API endpoint.
In the useEffect hook, the withLoader HOC fetches the data from the API
endpoint that we pass as the value of url. While the data hasn't returned yet,
we return the element containing the Loading... text.
Once the data has been fetched, we set data equal to the data that has been
fetched. Since data is no longer null, we can display the element that we
passed to the HOC!
So, how can we add this behavior to our application, so it'll actually show
the Loading... indicator on the DogImages list?
The withLoader HOC also expects the url to know which endpoint to fetch
the data from. In this case, we want to add the Dog API endpoint.
The Higher Order Component pattern allows us to provide the same logic to
multiple components, while keeping all the logic in one single place.
The withLoader HOC doesn’t care about the component or url it receives:
as long as it’s a valid component and a valid API endpoint, it’ll simply pass the
data from that API endpoint to the component that we pass.
Composing
We can also compose multiple Higher Order Components. Let's say that we
also want to add functionality that shows a Hovering! text box when the user
hovers over the DogImages list.
We need to create a HOC that provides a hovering prop to the element that
we pass. Based on that prop, we can conditionally render the text box based
on whether the user is hovering over the DogImages list.
We can now wrap the withHover HOC around the withLoader HOC.
The DogImages element now contains all props that we passed from
both withHover and withLoader. We can now conditionally render
the Hovering! text box, based on whether the value of the hovering prop
is true or false.
Let’s replace the withHover HOC with a useHover hook. Instead of having
a higher order component, we export a hook that adds
a mouseOver and mouseLeave event listener to the element. We cannot
pass the element anymore like we did with the HOC. Instead, we'll return
a ref from the hook for that should get the mouseOver and
mouseLeave events.
The useEffect hook adds an event listener to the component, and sets the
value hovering to true or false, depending on whether the user is currently
hovering over the element. Both the ref and hovering values need to be
returned from the hook: ref to add a ref to the component that should receive
the mouseOver and mouseLeave events, and hovering in order to be able to
conditionally render the Hovering! text box.
Generally speaking, React Hooks don't replace the HOC pattern. As the React
docs tell us, using Hooks can reduce the depth of the component tree. Using
the HOC pattern, it's easy to end up with a deeply nested component tree.
Using Higher Order Components makes it possible to provide the same logic
to many components, while keeping that logic all in one single place. Hooks
allow us to add custom behavior from within the component, which could
potentially increase the risk of introducing bugs compared to the HOC pattern
if multiple components rely on this behavior.
Best use-cases for a HOC:
• The component can work standalone, without the added custom logic.
• The behavior has to be customized for each component that uses it.
• The behavior is not spread throughout the application, only one or a few
components use the behavior.
Case Study
Some libraries that relied on the HOC pattern added Hooks support after the
release. A good example of this is Apollo Client.
One way to use Apollo Client is through the graphql() higher order
component.
import React from " react " ;
import " ./styles.css " ;
handleChange ( e ) => {
this.setState ( { message : e.target.value } ) ;
};
handleClick = ( ) => {
this.props.mutate ( { variables : { message : this.state.message } } ) ;
};
render ( ) {
return (
<div className = " input - row " >
< input
onChange={ this.handleChange }
type = " text"
placeholder = " Type something..."
/>
< button onclick={ this.handleClick } >Add < / button >
</ div >
);
}
}
After the release of Hooks, Apollo added Hooks support to the Apollo Client
library. Instead of using the graphql() higher order component, developers
can now directly access the data through the hooks that the library provides.
Pros
Using the Higher Order Component pattern allows us to keep logic that we
want to re-use all in one place. This reduces the risk of accidentally spreading
bugs throughout the application by duplicating code over and over, potentially
introducing new bugs each time. By keeping the logic all in one place, we can
keep our code DRY and easily enforce separation of concerns
Cons
The name of the prop that a HOC can pass to an element, can cause a
naming collision.
In this case, the withStyles HOC adds a prop called style to the element
that we pass to it. However, the Button component already had a prop
called style, which will be overwritten! Make sure that the HOC can handle
accidental name collision, by either renaming the prop or merging the props.
When using multiple composed HOCs that all pass props to the element that's
wrapped within them, it can be difficult to figure out which HOC is responsible
for which prop. This can hinder debugging and scaling an application easily.
Reuse existing instances when working with identical objects
The flyweight pattern is a useful way to conserve memory when we're creating
a large number of similar objects.
In our application, we want users to be able to add books. All books have
a title, an author, and an isbn number! However, a library usually doesn't have
just one copy of a book: it usually has multiple copies of the same book.
It wouldn't be very useful to create a new book instance each time if there are
multiple copies of the exact same book. Instead, we want to create multiple
instances of the Book constructor, that represent a single book.
Let's create the functionality to add new books to the list. If a book has the
same ISBN number, thus is the exact same book type, we don't want to create
an entirely new Book instance. Instead, we should first check whether this
book already exists.
If it doesn't contain the book's ISBN number yet, we'll create a new book and
add its ISBN number to the isbnNumbers set.
The createBook function helps us create new instances of one type of book.
However, a library usually contains multiple copies of the same book! Let's
create an addBook function, which allows us to add multiple copies of the
same book. It should invoke the createBook function, which returns either a
newly created Book instance, or returns the already existing instance.
Perfect! Instead of creating a new Book instance each time we add a copy,
we can effectively use the already existing Book instance for that particular
copy. Let's create 5 copies of 3 books: Harry Potter, To Kill a Mockingbird, and
The Great Gatsby.
Although there are 5 copies, we only have 3 Book instances!
The flyweight pattern is useful when you're creating a huge
number of objects, which could potentially drain all available RAM. It allows us
to minimize the amount of consumed memory.
With the factory pattern we can use factory functions in order to create new
objects. A function is a factory function when it returns a new object without
the use of the new keyword!
Say that we need many users for our application. We can create new users
with a firstName, lastName, and email property. The factory function
adds a fullName property to the newly created object as well, which returns
the firstName and the lastName.
pattern, we can easily create new objects that contain the custom keys and
values!
Pros
The factory pattern is useful when we have to create multiple smaller objects
that share the same properties. A factory function can easily return a custom
object depending on the current environment, or user-specific configuration.
Cons
In JavaScript, the factory pattern isn't much more than a function that returns
an object without using the new keyword. ES6 arrow functions allow us to
create small factory functions that implicitly return an object each time.
Context API
Let's look at an example: we have a list of squirrel images! Besides just
showing squirrel images, we want to add a button that makes it possible for
the user to edit or delete the image. We can implement a FlyOut component
that shows a list when the user toggles the component.
• The FlyOut wrapper, which contains the toggle button and the list
First, let's create the FlyOut component. This component keeps the state,
and returns a FlyOutProvider with the value of the toggle to all
the children it receives.
We now have a stateful FlyOut component that can pass the value
of open and toggle to its children!
Let's create the Toggle component. This component simply renders the
component on which the user can click in order to toggle the menu.
In order to actually give Toggle access to the FlyOutContext provider, we
need to render it as a child component of FlyOut! We could just simply
render this as a child component. However, we can also make
the Toggle component a property of the FlyOut component!
This means that if we ever want to use the FlyOut component in any file, we
only have to import FlyOut!
Just a toggle is not enough. We also need to have a List with list items,
which open and close based on the value of open.
The List component renders its children based on whether the value
of open is true or false. Let's make List and Item a property of
the FlyOut component, just like we did with the Toggle component.
We can now use them as properties on the FlyOut component! In this case,
we want to show two options to the user: Edit and Delete. Let's create
a FlyOut.List that renders two FlyOut.Item components, one for
the Edit option, and one for the Delete option.
You'll often see this pattern when using UI libraries like Semantic UI.
React.Children.map
All children components are cloned, and passed the value of open and toggle.
Instead of having to use the Context API like in the previous example, we now
have access to these two values through props.
import React from " react " ;
import Icon from ' ./Icon " ;
=
const FlyoutContext React.createContext ( ) ;
return (
< div >
function Toggle ( ) {
=
const { open , toggle } = React.useContext ( FlyoutContext ) ;
return (
<div className = " flyout - btn " onClick={ ( ) => toggle ( ! open ) }>
< Icon / >
< / div >
);
}
Flyout.Toggle = Toggle ;
Flyout.List List ;
Flyout . Item Item ;
Pros
Compound components manage their own internal state, which they share
among the several child components. When implementing a compound
component, we don't have to worry about managing the state ourselves.
Cons
When using the React.children.map to provide the values, the
component nesting is limited. Only direct children of the parent component will
have access to the open and toggle props, meaning we can't wrap any of
these components in another component.
Cloning an element with React.cloneElement performs a shallow merge.
Already existing props will be merged together with the new props that we
pass. This could end up in a naming collision, if an already existing prop has
the sameAs
method. name as theare
the props props we're passing
shallowly merged,tothe React.cloneElement
thevalue of that prop will be
With the Command Pattern, we can decouple objects that execute a certain
task from the object that calls the method.
Let's say we have an online food delivery platform. Users can place, track,
and cancel orders.
On the OrderManager class, we have access to
the placeOrder, trackOrder and cancelOrder methods. It would be
totally valid JavaScript to just use these methods directly!
Instead, we want to decouple the methods from the manager object, and
create separate command functions for each command!
• PlaceOrderCommand
• CancelOrderCommand
• TrackOrderCommand
class Command {
constructor ( execute ) {
this.execute = execute ;
}
}
function CancelOrderCommand ( id ) {
return new Command ( orders => {
orders =
orders.filter ( order => order.id ! == id ) ;
console.log ( " You have canceled your order $ { id } ' ) ;
});
}
function TrackorderCommand ( id ) {
=>
return new Command ( ( ).
console.log ( " Your order ${ id } will arrive in 20 minutes . ^ )
);
}
Cons
The use cases for the command pattern are quite limited, and often adds
unnecessary boilerplate to an application.
UNDER CONSTRUC
ONSTRUCT
DER CONSTRUCT
ION H UNDER CONSI
CAUTION !
A
WET FLOOR TII
=
RENDERING
Rendering content on the web can be done in many ways today. The decision
on how and where to fetch and render content is key to the performance of an
However, before we go into the available patterns or Next.js, let's take a look
at how we got here and what were the drivers that resulted in the creation of
the React framework and Next.js.
In the early 2000's we had sites where HTML content was rendered
completely by the server. Developers relied on server-side scripting languages
like PHP and ASP to render HTML. Page reloads were required for all key
navigations and JavaScript was used by clients minimally to hide/show or
enable/disable HTML elements.
Acronym Description
TTFB Time to First Byte - the time between clicking a link and the first bit of content coming
in.
FP First Paint - First time any content becomes visible to the user or the time when the
first few pixels are painted on the screen
FCP First Contentful Paint - Time when all the requested content becomes visible
LCP Largest Contentful Paint - Time when the main page content becomes visible. This
refers to the largest image or text block visible within the viewport.
TTI Time to Interactive - Time when the page becomes interactive e.g., events are wired
up, etc.
TBT Total Blocking Time - The total amount of time between FCP and TTI.
• A large JavaScript bundle could increase how long a page takes to reach
FCP and LCP. The user will be required to wait for some time to go from a
mostly blank page to a page with content loaded.
• Larger JavaScript bundles also affect TTI and TBT as the page can only
become interactive once the minimal required JavaScript is loaded and
We can now use these parameters to understand what exactly each pattern
has to offer with respect to rendering requirements.
Patterns - A Quick Look
Client-Side Rendering (CSR) and Server-Side Rendering (SSR) form the two
We will explore each of these patterns in detail. Before that, however, let us
talk about Next.js which is a React-based framework. Next.js is relevant to our
discussion because it can be used to implement all of the following patterns.
• SSR
• Static SSR (experimental flag)
• SSR with Rehydration
• CSR with Prerendering also known as Automatic Static Optimization
• Full CSR
Conclusion
We have now covered four patterns that are essentially variations of SSR.
These variations use a combination of techniques to lower one or more of the
performance parameters like TTFB (Static and Incremental Static Generation),
TTI (Progressive Hydration) and FCP/FP (Streaming). The patterns build upon
existing client-side frameworks like React and allow for some sort of
rehydration to achieve the interactivity levels of CSR. Thus, we have multiple
options to achieve the ultimate goal of combining both SSR and CSR benefits.
Summary
Depending on the type of the application or the page type, some of the
patterns may be more suitable than the others. The following chart revisits,
summarizes and compares the highlights of each pattern that we discussed in
the previous sections and provides use cases for each.
Vercel's framework for hybrid React applications
Let us explore the Next.js features that are relevant to our discussion
Basic Features
Pre-rendering
By default, Next.js generates the HTML for each page in advance and not on
the client-side. This process is called pre-rendering. Next.js ensures that
JavaScript code required to make the page fully interactive gets associated
with the generated HTML. This JavaScript code runs once the page loads. At
this point, React JS works in a Shadow DOM to ensure that the rendered
content matches with what the React application would render without actually
manipulating it. This process is called hydration.
Data Fetching
Next.js supports data fetching with both SSR and Static generation. Following
functions in the Next.js framework make this possible.
• getStaticProps
• getStaticPaths
• getServerSideProps
• Applicable to SSR
The image component can be served on the page using the following code.
Routing
Next.js supports routing through the pages directory. Every.js file in this
directory or its nested subdirectories becomes a page with the corresponding
route. Next.js also supports the creation of dynamic routes using named
parameters where the actual document displayed is determined by the value
of the parameter.
Consider this simple example for showing and updating the current time on a
page using React.
The HTML consists of just a single root div tag. Content display and updates
on the other hand are handled completely in JavaScript. There is no round trip
to the server and rendered HTML is updated in-place. Here time could be
replaced by any other real-time information like exchange rates or stock prices
obtained from an API and displayed without refreshing the page or a round trip
to the server.
As shown in the above illustration, as the size of bundle.js increases, the FCP
and TTI are pushed forward. This implies that the user will see a blank screen
for the entire duration between FP and FCP.
Client-side React - Pros and Cons
With React most of the application logic is executed on the client and it
interacts with the server through API calls to fetch or save data. Almost all of
the UI is thus generated on the client. The entire web application is loaded on
the first request. As the user navigates by clicking on links, no new request is
generated to the server for rendering the pages. The code runs on the client
to change the view/data.
This informs the browser to start loading the critical.js file before the page
rendering mechanism starts. The script will thus be available earlier and will
not block the page rendering mechanism thereby improving the performance.
1. Lazy loading: With lazy loading, you can identify resources that are non
critical and load these only when needed. Initial page load times can be
improved using this approach as the size of resources loaded initially is
reduced. For example., a chat widget component would generally not be
needed immediately on page load and can be lazy loaded.
2. Code Splitting: To avoid a large bundle of JavaScript code, you could start
splitting your bundles. Code-Splitting is supported by bundlers
like Webpack where it can be used to create multiple bundles that can be
dynamically loaded at runtime. Code splitting also enables you to lazy load
JavaScript resources.
content. SSR generates the full HTML for the page content to be rendered in
response to a user request. The content may include data from a datastore or
external API.
Server
Server
www.website.com
Server
www.website.com
Products
Blue Sneakers
Leather Boots
The connect and fetch operations are handled on the server. HTML required
to format the content is also generated on the server. Thus, with SSR we can
avoid making additional round trips for data fetching and templating. As such,
rendering code is not required on the client and the JavaScript corresponding
index.html
index.js
Note how this is different from the CSR code that provides the same output.
Also note that, while the HTML is rendered by the server, the time displayed
here is the local time on the client as populated by the JavaScript
function tick(). If you want to display any other data that is server specific,
e.g., server time, you will need to embed it in the HTML before it is rendered.
This means it will not get refreshed automatically without a round trip to the
server.
Executing the rendering code on the server and reducing JavaScript offers the
following advantages.
In cases where there are multiple UI elements and application logic on the
page, SSR has considerably less JavaScript when compared to CSR. The
time required to load and process the script is thus
lesser. FP, FCP and TTI are shorter and FCP = TTI. With SSR, users will not
be left waiting for all the screen elements to appear and for it to become
interactive.
Development teams are required to work with a JS budget that limits the
amount of JS on the page to achieve the desired performance. With SSR,
since you are directly eliminating the JS required to render the page, it creates
additional space for any third party JS that may be required by the application.
SEO enabled
Search engine crawlers are easily able to crawl the content of an SSR
application thus ensuring higher search engine optimization on the page.
SSR works great for static content due to the above advantages. However, it
does have a few disadvantages because of which it is not perfect for all
scenarios.
Slow TTFB
Since all processing takes place on the server, the response from the server
may be delayed in case of one or more of the following scenarios
• Multiple simultaneous users causing excess load on the server.
• Slow network
• Server code not optimized.
Since all code is not available on the client, frequent round trips to the server
are required for all key operations causing full page reloads. This could
increase the time between interactions as users are required to wait longer
between operations. A single-page application is thus not possible with SSR.
The Next.js framework also supports SSR. This pre-renders a page on the
server on every request. It can be accomplished by exporting an async
The context object contains keys for HTTP request and response objects,
routing parameters, querystring, locale, etc.
React can be rendered isomorphically, which means that it can function both
on the browser as well as other platforms like the server. Thus, UI elements
may be rendered on the server using React.
React can also be used with universal code which will allow the same code to
run in multiple environments. This is made possible by using Node.js on the
server or what is known as a Node server. Thus, universal JavaScript may be
used to fetch data on the server and then render it using isomorphic React.
Let us take a look at the react functions that make this possible.
This function returns an HTML string corresponding to the React element. The
HTML can then be rendered to the client for a faster page load.
To implement this, we use a .js file on both client and server corresponding
to every page. The .js file on the server will render the HTML content, and
the.js file on the client will hydrate it.
Assume you have a React element called App which contains the HTML to be
rendered defined in the universal app.js file. Both the server and client-side
React can recognize the App element.
A static HTML file is generated ahead of time corresponding to each route that
the user can access. These static HTML files may be available on a server or
As the name suggests, static rendering is ideal for static content, where the
page need not be customized based on the logged-in user (e.g personalized
recommendations). Thus static pages like the ‘About us', ‘Contact
us', Blog pages for websites or product pages for e-commerce apps, are ideal
candidates for static rendering. Frameworks like Next.js, Gatsby, and
VuePress support static generation. Let us start with this simple Next.js
example of static content rendering without any data.
pages/about.js
.
When the site is built, this page will be pre-rendered into an HTML
file about.html accessible at the route /about.
Static content like that in 'About us' or 'Contact us' pages may be rendered as
is without getting data from a data-store. However, for content like individual
blog pages or product pages, the data from a data-store has to be merged
with a specific template and then rendered to HTML at build time.
The number of HTML pages generated will depend on the number of blog
posts or the number of products respectively. To get to these pages, you may
also have listing pages which will be HTML pages that contain a categorized
and formatted list of data items. These scenarios can be addressed using
Next.js static rendering. We can generate listing pages or individual item
pages based on the available items. Let us see how.
function is called at build time on the build server to fetch the data. The data
can then be passed to the page's props to pre-render the page component.
The function will not be included in the client-side JS bundle and hence can
even be used to fetch the data directly from a database.
Assume we have products with product ids 101,102 103, and so on. We need
their information to be available at routes /products/101, /products/102, /
products/103 etc. To achieve this at build time in Next.js we can use the
function getStaticPaths() in combination with dynamic routes.
We need to create a common page component products/[id].js for this and
export the function getStaticPaths() in it. The function will return all possible
product ids which can be used to pre-render individual product pages at build
time. The following Next.js skeleton available here shows how to structure the
code for this.
pages/products/[id].js
The details on the product page may be populated at build time by using the
function getStaticProps for the specific product id. Note the use of the fallback:
false indicator here. It means that if a page is not available corresponding to a
specific route or product Id, the 404 error page will be shown.
Thus we can use SSG to pre-render many different types of pages.
Key Considerations
As discussed, SSG results in a great performance for websites as it cuts down
the processing required both on the client and the server. The sites are also
SEO friendly as the content is already there and can be rendered by web
crawlers with no extra effort. While performance and SEO make SSG a great
rendering pattern, the following factors need to be considered when assessing
the suitability of SSG for specific applications.
Static Generation (SSG) addresses most of the concerns of SSR and CSR
but is suitable for rendering mostly static content. It poses limitations when the
content to be rendered is dynamic or changing frequently.
Think of a growing blog with multiple posts. You wouldn't possibly want to
rebuild and redeploy the site just because you want to correct a typo in one of
the posts. Similarly, one new blog post should also not require a rebuild for all
the existing pages. Thus, SSG on its own is not enough for rendering large
websites or applications.
Let us now look at the Next.js code required for lazy-loading the non-existent
page with iSSG.
pages/products/[id ].js
if ( router.isFallback ) {
return < div> Loading ... </ div> ;
}
// Render product
}
Here, we have used fallback: true. Now if the page corresponding to a
specific product is unavailable, we show a fallback version of the page, eg., a
loading indicator as shown in the Product function above. Meanwhile, Next.js
will generate the page in the background. Once it is generated, it will be
cached and shown instead of the fallback page. The cached version of the
page will now be shown to any subsequent visitors immediately upon request.
For both new and existing pages, we can set an expiration time for when
Next.js should revalidate and update it. This can be achieved by using the
revalidate property as shown in the following section.
To re-render an existing page, a suitable timeout is defined for the page. This
will ensure that the page is revalidated whenever the defined timeout period
has elapsed. The timeout could be set to as low as 1 second. The user will
continue to see the previous version of the page, till the page has finished
Let us go back to the example for generating a static listing page for products
based on the data in the database. To make it serve a relatively dynamic list of
products, we will include the code to set the timeout for rebuilding the page.
This is what the code will look like after including the timeout.
pages/products/[id].js
iSSG provides all the advantages of SSG and then some more. The following
list covers them in detail.
1. Dynamic data: The first advantage is obviously why iSSG was envisioned.
Its ability to support dynamic data without a need to rebuild the site.
5. Ease of Distribution: Just like SSG sites, iSSG sites can also be
distributed through a network of CDN's used to serve pre-rendered web
pages.
Delay loading JavaScript for less important parts of the page
A server rendered application uses the server to generate the HTML for the
current navigation. Once the server has completed generating the HTML
contents, which also contains the necessary CSS and JSON data to display
the static UI correctly, it sends the data down to the client. Since the server
generated the markup for us, the client can quickly parse this and display it on
the screen, which produces a fast First Contentful Paint!
The time that the user sees non-interactive UI on the screen is also refered to
as the uncanny valley: although users may think that they can interact with the
website, there are no handlers attached to the components yet. This can be a
frustrating experience for the user, as the UI may can like it's frozen!
It can take a while before the DOM components that were received from the
server are fully hydrated. Before the components can be hydrated, the
JavaScript file needs to be loaded, processed, and executed. Instead of
client.js
server.js
For all components on the page to become interactive via hydration, the React
code for these components should be included in the bundle that gets
downloaded to the client. Highly interactive SPAs that are largely controlled by
JavaScript would need the entire bundle at once. However, mostly static
websites with a few interactive elements on the screen, may not need all
components to be active immediately. For such websites sending a huge
React bundle for each component on the screen becomes an overhead.
certain parts of the application when the page loads. The other parts are
hydrated progressively as required.
With Progressive hydration, the "You may also like" and "Other content"
components can be hydrated later.
Instead of initializing the entire application at once, the hydration step begins
at the root of the DOM tree, but the individual pieces of the server-rendered
application are activated over a period of time. The hydration process may be
arrested for various branches and resumed later when they enter the viewport
or based on some other trigger. Note that, the loading of resources required to
perform each hydration is also deferred using code-splitting techniques,
thereby reducing the amount of JavaScript required to make pages
interactive.
activating your app in chunks. Any progressive hydration solution should also
take into account how it will impact the overall user experience. You cannot
have chunks of screen popping up one after the other but blocking any activity
or user input on the chunks that have already loaded. Thus, the requirements
for a holistic progressive hydration implementation are as follows.
React concurrent mode can also be combined with another React feature
Server Components. This will allow you to refetch components from the
server and render them on the client as they stream in instead of waiting for
the whole fetch to finish. Thus, the client's CPU is put to work even as we wait
for the network fetch to finish.
hydrated.
Pros and Cons
hydration while also minimizing the cost of hydration. Following are some of
the advantages that can be gained from this.
On the downside, progressive hydration may not be suitable for dynamic apps
where every element on the screen is available to the user and needs to be
made interactive on load. This is because, if developers do not know where
the user is likely to click first, they may not be able to identify which
components to hydrate first.
Generate HTML to be rendered on the server in response to a user
request
We can reduce the TTI while still server rendering our application
by streaming server rendering the contents of our application. Instead of
generating one large HTML file containing the necessary markup for the
current navigation, we can split it up into smaller chunks! Node streams allow
us to data into the response object, which means that we can continuously
send data down to the client. The moment the client receives the chunks of
data, it can start rendering the contents.
FCP TTI
Network
GET /
GET /
bundle.js
FCP TTI
Network
GET /
GET /
bundle.js
const DELAY =
500 ;
const BEFORE
< ! DOCTYPE html >
<html >
< head >
<title>Cat Facts </ title>
<link rel = " stylesheet " href = " / style.css " >
< script type = "module " defer src = " /build / client.js " > < / script >
</ head >
< body>
< h1 >Stream Rendered Cat Facts ! < / h1>
<div id = " approot" >
` .replace ( /
s*/g , " " );
app.get ( " / " , async ( request , response ) => {
try {
const stream renderToNodeStream ( <App / > ) ;
const start = Date.now ( ) ;
This data contains useful information that our app has to use in order to
render the contents correctly, such as the title of the document and a
stylesheet. If we were to server render the App component using
the renderToString method, we would have had to wait until the application
has received all data before it can start loading and processing this metadata.
To speed this up, renderToNodeStream makes it possible for the app to start
loading and processing this information as it's still receiving the chunks of data
from the App component!
Concepts
• ReactDOMServer.renderToStaticNodeStream(element): This
corresponds
to ReactDOMServer.renderToStaticNodeStream(element). The
HTML output is the same but in a stream format. It can be used for
rendering static, non-interactive pages on the server and then streaming
them to the client.
The readable stream output by both functions can emit bytes once you start
reading from it. This can be achieved by piping the readable stream to a
writable stream such as the response object. The response object
progressively sends chunks of data to the client while waiting for new chunks
to be rendered.
A comparison between TTFB and First Meaningful Paint for normal SSR Vs
Streaming is available in the following image.
Pros and cons
Streaming aims to improve the speed of SSR with React and provides the
following benefits
1. Performance Improvement: As the first byte reaches the client soon after
rendering starts on the server, the TTFB is better than that for SSR. it is also
more consistent irrespective of the page size. Since the client can start
parsing HTML as soon as it receives it, the FP and FCP are also lower.
patterns that we have explored and try to understand their suitability for
different situations.
Server Components compliment SSR, rendering to an intermediate
abstraction without needing to add to the JavaScript bundle
The direction of this work is exciting, and while it isn't yet production ready, is
worth keeping on your radar. The RFC is worth reading as is Dan and
Lauren's talk worth watching for more detail.
Server Components
Server Components are not a replacement for SSR. When paired together,
they support quickly rendering in an intermediate format, then having Server
side rendering infrastructure rendering this into HTML enabling early paints to
still be fast. We SSR the Client components which the Server components
emit, similar to how SSR is used with other data-fetching mechanisms.
This time however, the JavaScript bundle will be significantly smaller. Early
explorations have shown that bundle size wins could be significant (-18-29%),
but the React team will have a clearer idea of wins in the wild once further
infrastructure work is complete.
Automatic Code-Splitting
It's been considered a best-practice to only serve code users need as they
need it by using code-splitting. This allows you to break your app down into
smaller bundles requiring less code to be sent to the client. Prior to Server
Components, one would manually use React.lazy() to define "split-points" or
rely on a heuristic set by a meta-framework, such as routes/pages to create
new chunks.
Some of the challenges with code-splitting are:
Some of the early integration work for Server Components will be done via a
webpack plugin which:
In previous articles, we covered how SSR with hydration can improve user
experience. React is able to (quickly) generate a tree on the server using
the renderToString method that the react-dom/server library provides, which
gets sent to the client after the entire tree has been generated. The rendered
HTML is non interactive, until the JavaScript bundle has been fetched and
loaded, after which React walks down the tree to hydrate and attaches the
handlers. However, this approach can lead to some performance issues due
to some limitations with the current implementation.
Before the server-rendered HTML tree is able to get sent to the client, all
components need to be ready. This means that components that may rely on
an external API call or any process that could cause some delays, might end
up blocking smaller components from being rendered quickly.
Besides a slower tree generation, another issue is the fact that React only
hydrates the tree once. This means that before React is able to hydrate any of
the components, it needs to have fetched the JavaScript for all of the
components before it’s able to hydrate any of them. This means that smaller
components (with smaller bundles) have to wait for the larger components’s
code to be fetched and loaded, until React is able to hydrate anything on your
website. During this time, the website remained non-interactive.
Server
<main >
Data Sources
< div id = " header " >
< h1>Buy Plant < /h1>
< / div >
< div id = " comments " >
☺
< ul>
< li > I love this plant ! < / li>
< li> The plant was very green . < /li >
< li >Looks amazing ! < / li >
< li > Easy to water < / li>
< li >Gorgeous flower ! < / li >
< / ul >
</div>
< div id = " footer " >
<a href="/contact">Contact</a>
</ div>
< / main>
Server
<main >
Data Sources
< div id = " header " >
<h1 >Buy Plant < /h1>
< / div > s
Server
www.website.com
<main>
<div id = " header " >
<h1 > Buy Plant < / h1>
</ div>
Server
www.website.com
<main >
< div id = " header " >
< h1 > Buy Plant < /h1>
< / div >
Server
www.website.com 0
BuyPlant
Jane Doe
I love this plant!
Sarah Smith
The plant was very green
John Doe
Looks amazing!
Anonymous
Easy to water
Anonymous
Gorgeous flower!
Contact
Server
www.website.com
BuyPlant
Jane Doe
I love this plant!
Sarah Smith
bundle1.js bundle2.js
The plant was very green
John Doe
Looks amazing !
bundle3.js
Anonymous
:B:
Easy to water
Anonymous
Gorgeous flower!
Contact
React 18 solves these problems by allowing us to combine streaming server
side rendering with a new approach to hydration: Selective Hydration!
index.js
server.js
The Comments component, which earlier slowed down the tree generation
and TTI, is now wrapped in Suspense. This tells React to not let this
component slow down the rest of the tree generation. Instead, React inserts
the fallback components as the initially rendered HTML, and continues to
generate the rest of the tree before it's sent to the client.
In the meantime, we're still fetching the external data that we need for
the Comments component.
Selective hydration makes it possible to already hydrate the components that
were sent to the client, even before the Comments component has been sent!
Once the data for the Comments component is ready, React starts streaming
the HTML for this component, as well as a small <script> to replace the
fallback loader.
React starts the hydration after the new HTML has been injected.
Server
www.website.com o
BuyPlant
Jane Doe
I love this plant!
Sarah Smith
The plant was very green
John Doe
Looks amazing !
Anonymous
Easy to water
Anonymous
Gorgeous flower!
Contact
Server
www.website.com
BuyPlant
Jane Doe
I love this plant!
Sarah Smith
The plant was very green
John Doe
bundle3.js
Looks amazing !
Anonymous
Easy to water
Anonymous
Gorgeous flower!
Contact
Server
www.website.com
BuyPlant
Anonymous onClick
Easy to water
Anonymous onClick
Gorgeousflower!
Contact
React 18 fixes some issues that people often encountered when using SSR
with React.
Cumulative Improvements
With that background, let's talk about every change implemented and how it
contributed to the overall performance improvement we achieved.
Packages Switched
Most of these attempts were extremely fruitful in bringing down the values of
different metrics
• Using @svgr/webpack instead of Font-Awesome for SVG icons helped to
boost Speed Index by 34%, LCP by 23%, and TBT by 51%
• Using a custom-built component to replace react-burger-menu and
removing the resize-observer-polyfill from react-sicky-
box led to a reduction in bundle size by 34.28 kB (gZipped).
• React Select Search was used instead of React Select which led to a 35%
improvement in the LCP with a 100% improvement in CLS and 18% in
TBT.
• The use of React Glider instead of React Slick improved TBT by 77%.
• Usage of React Scrolling instead of native smooth scrolling provided cross
browser compatibility for the scrolling feature.
• React Stars component was used instead of React Rating which helped to
boost TBT by 33%.
SVG icons were the obvious choice for all our icon needs across the Movies
app. We initially chose Font-Awesome due to its popularity and ease of use as
a scalable vector icon library with icons that are customizable using CSS.
However, there had been concerns that Font-Awesome may be slow to load
on web pages due to the large transfer sizes when loading the library. This
affects Lighthouse performance score.
Application Menu
This helped to reduce the bundle size corresponding to the burger menu
component considerably without affecting the required functionality. As seen in
the treemap analysis of the chunks before and after the change, the gzipped
size of the burger-menu chunk was 6.73 kB earlier but reduced to 879 B after
the change. The parsed size also went down from 32.74 kB to 2.14 kB. Thus,
the change helped to reduce both the download time as well as the parse time
for the chunk
Dropdown for Sort feature
The Movies app allows you to sort movies belonging to a particular genre or
starring a selected actor. You can sort by Popularity, Votes, Release Date, or
Original Title. To allow users to select a sort option, we had previously used
the react-select component. The component allows for multiple-select, search,
animation, and access to styling API using emotion. The bundle size for the
component is 27.2 kB minified and gzipped with 7 dependencies.
The following highlights the changes in the UI itself due to the component
change and corresponding improvement in Lighthouse performance.
Before
After
Cart Carousel
We had used the react-slick component on our movie pages that allowed
users to horizontally "glide" through the movie cast. The react-slick component
however is quite heavy when it comes to the bundle size. At 14.7 kB it comes
with 5 dependencies.
addition. In the future, we may rewrite this component to use CSS Scroll
Snap.
The Movies App implements pagination on the movie listing pages to switch
from one page to the other. Every time the previous or next page button is
clicked, the view needs to scroll to the top of the new page. For the transition
to be smooth, we had used the native smooth scroll function as follows.
Native smooth scroll functions are however not supported across all browsers.
To allow us to animate the vertical scrolling, we decided to use a scrolling
library called react-scroll (6.8 kB gzipped). This not only helped to
recreate the same scroll effect with a small regression in performance as can
be seen in the following comparison.
Metric
Performance FCP Speed LCP TBT CL Performa
(s) Index (s) (s) TTI (s) (ms) S nce (%)
react-rating, the rating component that we had originally used, allows you
to customize the look by using different symbols for rating; eg., stars, circles,
thumbs-up, etc. We had used the star symbol for rating earlier and did not
need the other features that were part of the library. The cost of including the
bundle for this component was 2.6kB.
The react-stars component served our purpose and we were able to show
star ratings for movies on the movie listing screen using this component too.
This component was only 2 kB minified and gzipped. We used this component
and inlined the source for further optimization.
Although, the library sizes do not look very different, the react-rating
component uses SVG icons for ratings while the react-stars component uses
the symbol "★". As the component gets repeated 20 times on the movie
listing page, the size of the icon/image also contributes to the overall savings
due to the component change. This is apparent from the Lighthouse scores
before and after the change.
Before
After
Code-Splitting
We used code-splitting to lazy-load the Menu component - being collapsed by
default on mobile, this was an opportunity to only do work when a user
actually needed it. We had initially tried lazy loading with the Burger Menu
sidebar component and observed some gain in performance. After we
replaced this with a custom component for the sidebar menu, we lazy-loaded
the custom component.
Metric
Performance FCP Speed LCP TBT CL Performa
(s) Index (s) (s) TTI (s) (ms) S nce (%)
Before 0.86 4.2 3.46 2.53 70 0 87.66
As part of our optimizations, we in-lined the CSS required for dark/light modes
transition which was identified as critical CSS.
As per Next.js documentation, we had initially imported all our node module
CSS files in the /pages/_app.js file. We are using two components react
glider and react-modal-video that require CSS import from node
modules. Importing this CSS through _app.js would be render-blocking for
the app as these components are not required on all the pages.
The CSS required by these components was inlined in the files where the
component was used. For example, after optimization, the code in our cast
component includes the syntax to render the Glider along with the styles that it
uses.
With this change, we were able to observe a slight change of 2% to 5% in
FCP, LCP, and TTI. The performance improved from 79% to 81% for the page.
feature.
Preconnects
Preconnects allow you to provide hints to the browser on what resources are
going to be required by the page shortly. Adding "rel=preconnect" informs
the browser that the page will need to establish a connection to another
domain so that it can start the process sooner. The hints help to load
resources quicker because the browser may have already set up the
connection by the time the resources are required.
Fetch the movie poster data Render the home page with the
fetched movie poster data.
With this knowledge, we were able to preload the data for the home page as
follows.
This was used only on the home page as we cannot predict what the users
will click/pick on the other pages. If the preloaded data is not used, it will be a
waste of resources resulting in a warning like this which can be seen in
Chrome Dev Tools - "The resource https://api.themoviedb.org/3/movie/
popular?api_key=844dba0bfd8f3a4f3799f6130ef9e335&page=1 was preloaded
using link preload but not used within a few seconds from the window's
preloaded intentionally.”
The LCP and TTI improved by 12.65% and 7.76% respectively after this
change while the overall performance went up from 91% to 94% for the home
page.
The movies app uses Next.js SSR to render the wrapper for the UI. Since the
app can be accessed on both desktop and mobile devices, responsive design
was essential. Combining responsive design with SSR has been a challenge
because:
1. The server where the content is rendered does not recognize the
client window element. Thus methods
like window.matchmedia() cannot be used to determine client details.
The following images compare the difference in markup rendered before and
after the change for the same content.
Before
After
Following is the change in Lighthouse performance observed after the
change.
While there is some regression in FCP, LCP, TTI, and TBT, the speed index
and performance have improved. The chunk size has increased due to the
contribution of the artsy/fresnel bundle. However, the reduction in markup may
make this a good trade-off.
Google analytics was included on the site so that we can get a better picture
of how the app engages with its users. Some regression was expected after
including Google Analytics. The change in performance was captured as per
our process to track performance variations for the code changes. There was
some regression as expected due to the inclusion of the analytics component.
Performance FCP Speed LCP TTI TBT CL Perform
Parameter (s) Index (s) (s) (s) (ms) S ance (%)
Before 0.8 3.4 2.53 1.8 26.66 0 95.66
Based on the Lighthouse report's feedback, there were some alternatives and
ideas that we tried but gave up because there were no performance benefits.
reduction in LCP. It is possible that native image lazy loading loads a few
images that are near the viewport while react lazy-load only loads those that
are within the viewport causing this difference in TBT.
Today, one could also use the Next.js Image Component to implement this
functionality. However, since the component uses JS internally, using an
HTML + CSS-based solution may perform better.
1. Before setting the aspect ratio for images, we had tried to improve CLS by
setting image dimensions. Even though it is one of the recommended
approaches for reducing CLS, setting image dimensions did not work so
well as the aspect ratio technique that we finally implemented.
Conclusion
The core principle for SSR is that HTML is rendered on the server and
shipped with necessary JavaScript to rehydrate it on the client. Rehydration is
the process of regenerating the state of UI components on the client-side after
the server renders it. Since rehydration comes at a cost, each variation of
SSR tries to optimize the rehydration process. This is mainly achieved
by partial hydration of critical components or streaming of components as they
get rendered. However, the net JavaScript shipped eventually in the above
techniques remains the same.
The term Islands architecture was popularized by Katie Sylor-Miller and Jason
Miller to describe a paradigm that aims to reduce the volume of JavaScript
shipped through "islands" of interactivity that can be independent delivered on
top of otherwise static HTML. Islands are a component-based architecture
that suggests a compartmentalized view of the page with static and dynamic
islands. The static regions of the page are pure non-interactive HTML and do
not need hydration. The dynamic regions are a combination of HTML and
scripts capable of rehydrating themselves after rendering.
Let us explore the Islands architecture in further detail with the different
options available to implement it at present.
• Blog posts, news articles, and organization home pages contain text and
images with interactive components like social media embeds and chat.
Static content is stateless, does not fire events, and does not need
rehydration after rendering. After rendering, dynamic content (buttons, filters,
search bar) has to be rewired to its events. The DOM has to be regenerated
on the client-side (virtual DOM). This regeneration, rehydration, and event
handling functions contribute to the JavaScript sent to the client.
You can use one of the out-of-the-box options discussed next to implement
this.
Frameworks
• Astro: Astro is a static site builder that can generate lightweight static
HTML pages from UI components built in other frameworks such as
React, Preact, Svelte, Vue, and others. Components that need client-side
JavaScript are loaded individually with their dependencies. Thus it
provides built-in partial hydration. Astro can also lazy-load components
depending on when they become visible. We have included a sample
implementation using Astro in the next section.
The following is a sample blog page that we have implemented using Astro.
The page SamplePost imports one interactive component, SocialButtons. This
component is included in the HTML at the required position via markup.
SamplePost.astro
The SocialButtons component is a Preact component with its HTML, and
corresponding event handlers included.
SocialButtons.tsx
The component is embedded in the page at run time and hydrated on the
client-side so that the click events function as required.
Astro allows for a clean separation between HTML, CSS, and scripts and
encourages component-based design. It is easy to install and start building
websites with this framework.
Comparisons for Astro with documentation websites created for Next.js and
Nuxt.js have shown an 83% reduction in JavaScript code. Other users have
also reported performance improvements with Astro.
• SEO: Since all of the static content is rendered on the server; pages are
SEO friendly.
Despite the advantages, the concept is still in a nascent stage. The limited
support results in some disadvantages.
• The architecture is not suitable for highly interactive pages like social
media apps which would probably require thousands of islands.
The Islands architecture concept is relatively new but likely to gain speed due
to its performance advantages. It underscores the use of SSR for rendering
static content while supporting interactivity through dynamic components with
minimal impact on the page's performance. We hope to see many more
players in this space in the future and have a wider choice of implementation
options available.
PERFORMANCE
Learn how to optimize your loading sequence to improve how quickly
your app is usable
Note: This article is heavily influenced by insights from the Aurora team in
Chrome, in particular Shubhie Panicker who has been researching the optimal
loading sequence.
In every successful web page load, some critical components and resources
become available at just the right time to give you a smooth loading
experience. This ensures users perceive the performance of the application to
be excellent. This excellent user experience should generally also translate to
passing the Core Web Vitals.
Key metrics such as First Content Paint, Largest Contentful Paint, First Input
There is often a critical gap between developers' expectations and how the
browser prioritizes resources on the page. This often results in sub-optimal
performance scores. We analyzed further to discover what caused this gap
and the following points summarize the essence of our analysis.
Sub-optimal sequencing
Web Vitals optimization requires not only a good understanding of what each
metrics stands for but also the order in which they occur and how they relate
to different critical resources. FCP occurs before LCP which occurs before
FID. As such, resources required for achieving FCP should be prioritized over
those required by LCP followed by those required by FID.
Resources are often not sequenced and pipelined in the correct order. This
may be because developers are not aware of the dependency of metrics on
resource loads. As a result, relevant resources are sometimes not available at
the right time for the corresponding metric to trigger.
Examples:
a) By the time FCP fires, the hero image should be available for firing LCP.
b) By the time LCP fires, the JavaScript (JS) should be downloaded, parsed
and ready (or already executing) to unblock interaction (FID).
Network/CPU Utilization
Resources are also not pipelined appropriately to ensure full CPU and
Network utilization. This results in "Dead Time" on the CPU when the process
is network bound and vice versa.
3P products don't usually have an incentive to optimize for and support the
consumer site's loading performance. They could have a heavy JavaScript
execution cost that delays interactivity, or gets in the way of other critical
resources being downloaded.
Developers who include 3P products may tend to focus more on the value
they add in terms of features rather than performance implications. As a
result, 3P resources are sometimes added haphazardly, without full
consideration in terms of how it fits into the overall loading sequence. This
makes them hard to control and schedule.
Platform Quirks
Browsers may differ in how they prioritize requests and implement hints.
Optimization is easier if you have a deep knowledge of the platform and its
quirks. Behavior particular to a specific browser makes it difficult to achieve
the desired loading sequence consistently.
HTTP2 Prioritization
The protocol itself does not provide many options or knobs for adjusting the
order and priority of resources. Even if better prioritization primitives were to
be made available, there are underlying problems with HTTP2 prioritization
that make optimal sequencing difficult. Mainly, we cannot predict in what order
servers or CDN's will prioritize requests for individual resources. Some CDN's
re-prioritize requests while others implement partial, flawed, or no
prioritization.
Resource level optimization
Effective sequencing needs that the resources that are being sequenced to be
served optimally so that they will load quickly. Critical CSS should be inlined,
Images should be sized correctly and JS should be code-split and delivered
incrementally.
The framework itself is lacking constructs that allow code-splitting and serve
JS and data incrementally. Users must rely on one of the following to split
large chunks of 1P JS
2. Lazy loading using dynamic imports - This is not intuitive and developers
need to manually identify the boundaries along which to split the code.
As you might have noticed, these issues are not limited to a particular set of
resources or platforms. To work around these problems, one requires an
understanding of the entire tech stack and how different resources can be
coalesced to achieve optimal metrics. Before we define an overall optimization
strategy, let us look at how individual resource requirements can defeat our
purpose.
In the previous section, we gave a few examples of how certain resources are
required for a specific event like FCP or LCP to fire. Let us try to understand
all such dependencies first before we discuss a way to work with them.
Following is a resource-wise list of recommendations, constraints, and
gotchas that need to be considered before we define an ideal sequence.
Critical CSS
Critical CSS refers to the minimum CSS required for FCP. It is better to inline
such CSS within HTML rather than import it from another CSS file. Only the
CSS required for the route should be downloaded at any given time and all
If inlining is not possible, critical CSS should be preloaded and served from
the same origin as the document. Avoid serving critical CSS from multiple
domains or direct use of 3rd party critical CSS like Google Fonts. Your own
server could serve as a proxy for 3rd party critical CSS instead.
Delay in fetching CSS or incorrect order of fetching CSS could impact FCP
and LCP. To avoid this, non-inlined CSS should be prioritized and ordered
above 1P JS and ABT images on the network.
Too much inlined CSS can cause HTML bloating and long style parsing times
on the main thread. This can hurt the FCP. As such identifying what is critical
and code-splitting are essential.
Inlined CSS cannot be cached. One workaround for this is to have a duplicate
request for the CSS that can be cached. Note however, that this can result in
multiple full-page layouts which could impact FID.
Fonts
Like critical CSS, the CSS for critical fonts should also be inlined. If inlining is
not possible the script should be loaded with a preconnect specified. Delay in
fetching fonts, e.g., google fonts or fonts from a different domain can affect
FCP. Preconnect tells the browser to set up connections to these resources
earlier.
Inlining fonts can bloat the HTML significantly and delay initiating other critical
resource fetches. Font fallback may be used to unblock FCP and make the
text available. However, using font fallback can affect CLS due to jumping
fonts. It can also affect FID due to a potentially large style and layout task on
the main thread when the real font arrives.
metric because of the layout shift that occurs when they are fully rendered.
Placeholders for ABT images should be rendered by the server.
3P JavaScript
3P sync script in HTML head could block CSS & font parsing and therefore
FCP. Sync script in the head also blocks HTML body parsing. 3P script
execution on the main thread can delay 1P script execution and push out
hydration and FID. As such, better control is required for loading 3P scripts.
Preload *
XSL
• CSS and Fonts are loaded with the highest priority. This should help us
prioritize critical CSS and fonts.
• Scripts get different priorities based on where they are in the document and
whether they are async, defer, or blocking. Blocking scripts requested
before the first image ( or an image early in the document) are given higher
priority over blocking scripts requested after the first image is fetched.
• Images that are visible and in the viewport have a higher priority (Net:
Medium) than those that are not in the viewport (Net: Lowest). This helps
us prioritize ABT images over BTF images.
Let us now see how all of the above details can be put together to define an
optimal loading sequence.
Current State
Based on our experience, the following is the typical loading sequence we
have observed for a Next.js SSR application before optimization.
CSS CSS is preloaded before JS but is not inlined
JavaScript 1P JS is preloaded
3P JS is not managed and can still be render-blocking anywhere in the document.
Following is an example of one such sequence from one of our partner sites.
The positives and negatives about the loading sequence are included as
annotations.
Proposed Sequence without 3P
Following is a loading sequence that takes into account all of the constraints
discussed previously. Let us first tackle a sequence without 3P. We will then
see how 3P resources can be interleaved in this sequence. Note that, we
have considered Google Fonts as 1P here.
images
Visually Complete
6 Parse Non-critical
(async) CSS
While some parts of this sequence may be intuitive, the following points will
help to justify it further.
8
Non-critical (async) CSS
First-party JS for 10
interactivity
The main concern here is how do you ensure that 3P scripts are downloaded
optimally and in the required sequence.
Since the script request goes to another domain, preconnect is recommended
for the following 3P requests. This helps to optimize the download.
After-Interactive: Loads the specific 3P script after the next hydration. This
can be used to load Tag-managers, Ads, or Analytics scripts that we want to
Lazy-Onload: Prioritize all other resources over the specified 3P script and
lazy load the script. It can be used for CRM components like Google
Feedback or Social Network specific scripts like those used for share buttons,
comments, etc.
Thus, preconnect, script attributes and ScriptLoader for Next.js together can
help us get the desired sequence for all our scripts.
Conclusion
The responsibility of optimizing apps falls on the shoulders of the creators of
the platforms used as well as the developers who use it. Common issues
need to be addressed. We aim to make sequencing easier from the inside out.
A tried and tested set of recommendations for different use cases and
initiatives like the Script Loader help to achieve this for the React-Next.js
stack. The next step would be to ensure that new apps conform to the
recommendations above.
With special thanks to Leena Sohoni (Technical Analyst/Writer), for all her
contributions to this write-up.
Import code that has been exported by another module
The import keyword allows us to import code that has been exported by
another module. By default, all modules we're statically importing get added to
the initial bundle. A module that is imported by using the default ES2015
import syntax, import module from 'module', is statically imported.
Bundle
const ChatInput =
( ) == > { ... }
Bundle
Luckily, there are many ways to speed up the loading time! We don't always
have to import all modules at once: maybe there are some modules that
should only get rendered based on user interaction, like the EmojiPicker in
this case, or rendered further down the page. Instead of importing all
component statically, we can dynamically import the modules after
the App component has rendered its contents and the user is able to interact
with our application.
Import parts of your code on demand
The EmojiPicker isn't directly visible, and may not even be rendered at all if
the user won't even click on the emoji in order to toggle the EmojiPicker.
This would mean that we unnecessarily added the EmojiPicker module to
our initial bundle, which potentially increased the loading time!
When the user clicks on the emoji, the EmojiPicker component gets
rendered for the first time. The EmojiPicker component renders
a Suspense component, which receives the lazily imported module:
the EmojiPicker in this case. The Suspense component accepts
a fallback prop, which receives the component that should get rendered while
the suspended component is still loading!
Whereas previously the initial bundle was 1.5 MiB, we've been able to
reduce it to 1.33 MiB by suspending the import of the EmojiPicker!
www.website.com
John Doe
. online
especially on mobile...
OR WEBSITE NOTWORKING
Type a message ..
www.website.com
John Doe
• online
especially on mobile...
I agree, it's frustrating ! They should
use better loading patterns to keep
bundle bundle their users happy and optimize
loading performance !
main emoji-picker Yes!
Type a message .
www.website.com
John Doe
• online
OR WEBS
Type a message.
In the console, you can see that the EmojiPicker doesn't get executed until
we've toggled the EmojiPicker!
When building the application, we can see the different bundles that Webpack
created.
Besides user interaction, we often have components that aren't visible on the
initial page. A good example of this is lazy loading images that aren't directly
visible in the viewport, but only get loaded once the user scrolls.
As we're not requesting all images instantly, we can reduce the initial loading
time. We can do the same with components! In order to know whether
components are currently in our viewport, we can use the
IntersectionObserver API, or use libraries such as react-lazyload
or react-loadable-visibility to quickly add import on visibility to our
application.
Whenever the EmojiPicker is rendered to the screen, after the
user clicks on the Gif button, react-loadable
visibility detects that the EmojiPicker element should be visible on the
screen. Only then, it will start importing the module while the user sees a
loading component being rendered.
www.website.com
John Doe
• online
especially on mobile.
I agree, it's frustrating! They should
use better loading patterns to keep
bundle their users happy and optimize
loading performance !
main Yes!
Type a message.
www.website.com o
John Doe
• online
NOT SURE
OR WEBS
Type a message..
The fallback component lets the user know that our application hasn't frozen:
they simply need to wait a short while for the module to be loaded, parsed,
compiled, and executed!
Load non-critical resources when a user interacts with UI requiring it
Your page may contain code or data for a component or resource that isn’t
immediately necessary. For example, part of the user-interface a user doesn't
see unless they click or scroll on parts of the page. This can apply to many
kinds of first-party code you author, but this also applies to third-party widgets
such as video players or chat widgets where you typically need to click a
Loading these resources eagerly (right away) can block the main thread if
they are costly, pushing out how soon a user can interact with more critical
parts of a page. This can impact interaction readiness metrics like First Input
Delay, Total Blocking Time and Time to Interactive. Instead of loading
these resources immediately, you can load them at a more opportune
• When the user clicks to interact with that component for the first time
• Eager: load resource right away (the normal way of loading scripts)
• Lazy (On interaction): load when the user clicks UI (e.g Show Chat)
• Lazy (In viewport): load when the user scrolls towards the component
• Prefetch: load prior to needed, but after critical resources are loaded
Import on interaction for first-party code should only be done if you’re unable
to prefetch resources prior to interaction. The pattern is however very relevant
for third-party code, where you generally want to defer it if non-critical to a
later point in time. This can be achieved in many ways (defer until interaction,
until the browser is idle or using other heuristics).
You might be importing a third-party script and have less control over what it
renders or when it loads code. One option for implementing load-on-
Third-party resources are often added to pages without full consideration for
how they fit into the overall loading of a site. Synchronously-loaded third-party
scripts block the browser parser and can delay hydration. If possible, 3P script
should be loaded with async/defer (or other approaches) to ensure 1P scripts
aren't starved of network bandwidth. Unless they are critical, they can be a
good candidate for shifting to deferred late-loading using patterns like import
on-interaction.
Video Player Embeds
A good example of a "facade" is the YouTube Lite Embed by Paul Irish. This
provides a Custom Element which takes a YouTube Video ID and presents a
minimal thumbnail and play button. Clicking the element dynamically loads the
full YouTube embed code, meaning users who never click play don’t pay the
cost of fetching and processing it.
Authentication
costs and one might rather not eagerly load them up front if a user isn’t going
to login. Instead, dynamically import authentication libraries when a user clicks
on a "Login" button, keeping the main thread more free during initial load.
Chat Widgets
Postmark noted that their Help chat widget was always eagerly loaded, even
though it was only occasionally used by customers. The widget would pull in
314KB of script, more than their whole home page. To improve user
experience, they replaced the widget with a fake replica using HTML and
CSS, loading the real-thing on click. This change reduced Time to Interactive
from 7.7s to 3.7s.
Vanilla JavaScript
In JavaScript, dynamic import() enables lazy-loading modules and returns a
promise and can be quite powerful when applied correctly. Below is an
example where dynamic import is used in a button event listener to import the
Imagine a user is planning a trip to Mumbai, India and they visit Google Hotels
to look at prices. All of the resources needed for this interaction could be
loaded eagerly upfront, but if a user hasn’t selected any destination, the
HTML/CSS/JS required for the map would be unnecessary.
In the simplest download scenario, imagine Google Hotels is using
naive client-side rendering (CSR). All the code would be downloaded and
processed upfront: HTML, followed by JS, CSS and then fetching the data,
only to render once we have everything. However, this leaves the user waiting
a long time with nothing displayed on-screen. A big chunk of the JavaScript
and CSS may be unnecessary.
Next, imagine this experience moved to server-side rendering (SSR). We
would allow the user to get a visually complete page sooner, which is great,
however it wouldn’t be interactive until the data is fetched from the server and
the client framework completes hydration.
SSR can be an improvement, but the user may have an uncanny valley
experience where the page looks ready, but they are unable to tap on
anything. Sometimes this is referred to as rage clicks as users tend to click
over and over again repeatedly in frustration.
Only very minimal code is downloaded initially and beyond this, user
First, we download the minimal code initially so the page is visually complete
quickly.
Next, as the user starts interacting with the page we use those interactions to
determine which other code to load. For example loading the code for the
"more filters" component. This means code for many features on the page are
never sent down to the browser, as the user didn’t need to use them.
How do we avoid losing early clicks?
In the framework stack used by these Google teams, we can track clicks early
because the first chunk of HTML includes a small event library (JSAction)
which tracks all clicks before the framework is bootstrapped. The events are
used for two things:
The initial data which is used to render the page is included in the initial
page’s SSR HTML and streamed. Data that is late loaded is downloaded
based on user interactions as we know what component it goes with.
This completes the import-on-interaction picture with data-fetching working
similar to how CSS and JS function. As the component is aware of what code
and data it needs, all of its resources are never more than a request away.
For a walkthrough of the above example, see Elevating the Web Platform with
the JavaScript Community.
Trade-offs
Shifting costly work closer to user-interaction can optimize how quickly pages
initially load, however the technique is not without trade-offs.
What happens if it takes a long time to load a script after the user
clicks?
In the Google Hotels example, small granular chunks minimize the chance a
user is going to wait long for code and data to fetch and execute. In some of
the other cases, a large dependency may indeed introduce this concern on
slower networks.
One way to reduce the chance of this happening is to better break-up the
loading of, or prefetch these resources after critical content in the page is
done loading. I’d encourage measuring the impact of this to determine how
While static replacements can be good for performance, they do often require
doing something custom so keep this in mind when evaluating your options.
Conclusions
First-party JavaScript often impacts the interaction readiness of modern pages
on the web, but it can often get delayed on the network behind non-critical JS
from either first or third-party sources that keep the main thread busy.
With special thanks to Shubhie Panicker, Connor Clark, Patrick Hulce, Anton
Karlovskiy and Adam Raine for their input.
Dynamically load components based on the current route
We can request resources that are only needed for specific routes, by
adding route-based splitting. By combining React Suspense with libraries
such as react-router, we can dynamically load components based on the
current route.
By lazily loading the components per route, we're only
requesting the bundle that contains the code that's necessary
for the current route. Since most people are used to the fact that there may be
some loading time during a redirect, it's the perfect place to lazily load
components!
Split your code into small, reusable pieces
JavaScript engines such as V8 are able to parse and compile data that's been
requested by the user as it's being loaded. Although modern browsers have
evolved to parse and compile the code as quickly and performant as possible,
the developer is still in charge of optimizing two steps in the process:
the loading time and execution time of the requested data. We want to make
sure we're keeping the execution time as short as possible to prevent blocking
the main thread
Even though modern browsers are able to stream the bundle as it arrives, it
can still take a significant time before the first pixel is painted on the user's
device. The bigger the bundle the longer it can take before the engine reaches
the line on which the first rendering call has been made. Until that time, the
user has to stare at a blank screen for quite some time, which can be.. highly
frustrating!
We want to display data to the user as quickly as possible. A larger bundle
leads to an increased amount of loading time, processing time, and execution
time. It would be great if we could reduce the size of this bundle, in order to
speed things up.
Although being able to see data on our screen is great, we don't just want
to see the content. In order to have a fully functioning application, we want
users to be able to interact with it as well! The UI only becomes interactive
after the bundle has been loaded and executed. The time it takes before all
content has been painted to the screen and has been made interactive, is
called the Time To Interactive.
A bigger bundle doesn't necessarily mean a longer execution time. It could
happen that we loaded a ton of code that the user won't even use! Maybe
some parts of the bundle will only get executed on a certain user interaction,
which the user may or may not do!
The engine still has to load, parse and compile code that's not even used on
the initial render before the user is able to see anything on their screen.
Although the parsing and compilation costs can be practically ignored due to
the browser's performant way of handling these two steps, fetching a larger
bundle than necessary can hurt the performance of your application. Users on
low-end devices or slower networks will see a significant increase in loading
time before the bundle has been fetched.
Executable Code
Network
Parser + Compiler
Cache
Service Worker
www.website.com o
www.website.com
John Doe
• online
Type a message..
www.website.com
John Doe
online
especially on mobile...
Yes!
Type a message.
The first part still had to be loaded and processed, even though the engine
only used the last part of the file in order to . Instead of intially requesting parts
of the code that don't have a high priority in the current navigation, we can
separate this code from the code that's needed in order to render the initial
page.
By bundle-splitting the large bundle into two smaller
bundles, main.bundle.js and emoji-picker.bundle.js, we reduce
the initial loading time by fetching a smaller amount of data.
In this project, we'll cover some methods that allow us to bundle-split our
application into multiple smaller bundles, and load the resources in the most
efficient and performant ways.
Optimize initial load through precaching, lazy loading, and minimizing
roundtrips
• Rendering the initial route soon as possible to improve the user experience
When we want to visit a website, we first have to make a request to the server
in order to get those resources. The file that the entrypoint points to gets
returned from the server, which is usually our application’s initial HTML file!
The browser’s HTML parser starts to parse this data as soon as it starts
receiving it from the server. If the parser discovers that more resources are
needed, such as stylesheets or scripts, another HTTP request is sent to the
server in order to get those resources!
Having to repeatedly request the resources isn’t optimal, as we’re trying to
minimize the amount of round trips between the client and the server!
Once the server has received all request frames for that specific request, it
reassembles them and generates response frames. These response frames
are sent back to the client, which reassembles them. Since the stream is
bidirectional, we can send both request and response frames over the
same stream.
HTTP/2 solves head of line blocking by allowing multiple requests to get sent
on the same TCP connection before the previous request resolves!
HTTP/2 also introduced a more optimized way of fetching data, called server
push. Instead of having to explicitly ask for resources each time by sending an
HTTP request, the server can send the additional resources automatically, by
“pushing” these resources.
After the client has received the additional resources, the resources will get
stored in browser cache. When the resources get discovered while parsing
the entry file, the browser can quickly get the resources from cache instead of
having to make an HTTP request to the server!
Although pushing resources reduces the amount of time to receive additional
resources, server push is not HTTP cache aware! The pushed resources
won’t be available to us the next time we visit the website, and will have to be
requested again. In order to solve this, the PRPL pattern uses service
workers after the initial load to cache those resources in order to make sure
the client isn’t making unnecessary requests.
As the authors of a site, we usually know what resources are critical to fetch
early on, while browsers do their best to guess this. Luckily, we can help the
browser by adding a preload resource hint to the critical resources!
By telling the browser that you’d like to preload a certain resource, you’re
telling the browser that you would like to fetch it sooner than the browser
would otherwise discover it! Preloading is a great way to optimize the time it
takes to load resources that are critical for the current route.
A browser has a hard time identifying which parts of the bundle are shared
between multiple routes, and can therefore not cache these resources.
Caching resources is important to reduce the number of roundtrips to the
server, and to make our application offline-friendly!
When working with the PRPL pattern, we need to make sure that the bundles
we’re requesting contain the minimal amount of resources we need at that
time, and are cachable by the browser. In some cases, this could mean that
having no bundles at all would be more performant, and we could simply work
with unbundled modules!
The PRPL pattern often uses an app shell as its main entry point, which is a
minimal file that contains most of the application’s logic and is shared between
routes! It also contains the application’s router, which can dynamically request
the necessary resources.
www.website.com Server
app- shell.html
GET app- shell.html
app-shell.css
app- shell.js
Abu
www.website.com Server
BuyPlant Q
III
The PRPL pattern makes sure that no other resources get requested or
rendered before the initial route is visible on the user’s device. Once the initial
route has been loaded successfully, a server worker can get installed in order
to fetch the resources for the other frequently visited routes in the background!
www.website.com o
BuyPlant Q Server
Beautiful Plant
$ 50 145 reviews
Buy Now
Server
www.website.com
menu.html menu.css
BuyPlant Q
menu.js
Service Worker
Beautiful Plant
$ 50 145 reviews
Buy Now
Server
www.website.com
menu.html menu.css
= BuyPlant Q
menu.js
Service Worker
11
Beautiful Plant
$50 145 reviews
Buy Now
Server
www.website.com
o
BuyPlant
Service Worker
cache
Buy Now
Server
www.website.com
= BuyPlant Q
Service Worker
nenu .
menu.js
cache
2nu.css
Beautiful Plant
$ 50 145 reviews
Buy Now
Server
www.website.com
Menu Х
Home
Orders
Inspiration
Service Worker
All Plants
Settings
Billing
cache
Upgrade to Pro
o
Since this data is being fetched in the background, the user won’t experience
any delays. If a user wants to navigate to a frequently visited route that’s been
cached by the service worker, the service worker can quickly get the required
resources from cache instead of having to send a request to the server.
It can happen that we add code to our bundle that isn't used anywhere in our
application. This piece of dead code can be eliminated in order to reduce the
size of the bundle, and prevent unnecessarily loading more data! The process
of eliminating dead code before adding it to our bundle, is called tree-shaking
Although tree-shaking works for simple modules like the math module, there
are some cases in which tree-shaking can be tricky.
Concepts
Tree shaking is aimed at removing code that will never be used from a final
JavaScript bundle. When done right, it can reduce the size of your JavaScript
bundles and lower download, parse and (in some cases) execution time. For
most modern JavaScript apps that use a module bundler (like webpack or
Rollup), your bundler is what you would expect to automatically remove dead
code.
Consider your application and its dependencies as an abstract syntax tree (we
want to "shake" the syntax tree to optimize it). Each node in the tree is a
dependency that gives your app functionality. In Tree shaking, input files are
treated as a graph. Each node in the graph is a top level statement which is
called a "part" in the code. Tree shaking is a graph traversal which starts from
the entry point and marks any traversed paths for inclusion.
Every component can declare symbols, reference symbols, and rely on other
files. Even the "parts" are marked as having side effects or not. For example,
the statement let firstName = 'Jane' has no side effects because the
statement can be removed without any observed difference if nothing needs
foo. But the statement let firstName = getName() has side effects,
because the call to getName() can not be removed without changing the
meaning of the code, even if nothing needs firstName.
Imports
Only modules defined with the ES2015 module syntax (import and export) can
be tree-shaken. The way you import modules specifies whether the module
can be tree-shaken or not.
Tree shaking starts by visiting all parts of the entry point file with side effects,
and proceeds to traverse the edges of the graph until new sections are
reached. Once the traversal is completed, the JavaScript bundle includes only
the parts that were reached during the traversal. The other pieces are left out.
Let's say we define the following utilities.js file:
Then we have the following index.js file:
In this example, nap() isn't important and therefore won't be included in the
bundle.
Side Effects
When we're importing an ES6 module, this module gets executed instantly. It
could happen that although we're not referencing the module's exports
anywhere in our code, the module itself affects the global scope while it's
being executed (polyfills or global stylesheets, for example). This is called
a side effect. Although we're not referencing the exports of the module
itself, if the module has exported values to begin with, the module cannot
be tree-shaken due to the special behavior when it's being imported!
metrics in the Core Web Vitals. That said, preload is not a panacea and
requires an awareness of some trade-offs.
If you are trying to optimize the loading of first-party JavaScript, you can also
consider using <script defer> in the document <head> vs. <body> to
help with early discover of these resources.
const EmojiPicker =
lazy ( ( =>
import (" ./ EmojiPicker " ) ) ;
const ChatInput ( ) =>> {
const [ pickerOpen , togglePicker ] = React.useReducer ( state => ! state , true ) ;
return (
<div className= " chat - input - container " >
< input type = " text " placeholder = " Type a message ..." / >
< Emoji onclick={ togglePicker } / >
{ pickerOpen && (
< Suspense fallback={ < p id = " loading " > loading < / p > } >
<EmojiPicker / >
< / Suspense>
)}
< Send / >
GET /
GET /main.bundle.js
GET /emoji-picker.bundle.js
GET /
GET /main.bundle.js
GET /emoji-picker.bundle.js
After building the application, we can see that the EmojiPicker will be
prefetched.
Instead of having to wait until the EmojiPicker gets loaded after the initial
render, the resource will be available to us instantly! As we're loading assets
with smarter ordering, the initial loading time may increase significantly
depending on your users device and internet connection. Only preload the
resources that have to be visible ~1 second after the initial render.
Preload + the async hack
Should you wish for browsers to download a script as high-priority, but not
block the parser waiting for a script, you can take advantage of the preload
+ async hack below. The download of other resources may be delayed by the
preload in this case, but this is a trade-off a developer has to make:
Conclusions
Again, use preload sparingly and always measure its impact in production. If
the preload for your image is earlier in the document than it is, this can help
browsers discover it (and order relative to other resources). When used
incorrectly, preloading can cause your image to delay First Contentful Paint
(e.g CSS, Fonts) - the opposite of what you want. Also note that for such
reprioritization efforts to be effective, it also depends on servers prioritizing
requests correctly.
You may also find <link rel="preload"> to be helpful for cases where
you need to fetch scripts without executing them.
Fetch and cache resources that may be requested some time soon
interaction, we saw that there was often some delay between clicking on the
button in order to toggle the component, and showing the actual component
on the screen. This happened, since the module still had to get requested and
loaded when the user clicked on the button!
www.website.com
John Doe
• online
main Yes !
OR WEBSITENOTWORKING
Type a message.
www.website.com
John Doe
• online
especially on mobile...
I agree, it's frustrating! They should
use better loading patterns to keep
bundle their users happy and optimize
loading performance!
main Yes !
NOT SURE IF INTERNETS SLOW
OR WEBSITE NOTWORKING
Type a message .
www.website.com
John Doe
• online
Browser Idle
Hey how's it going!
especially on mobile...
I agree, it's frustrating! They should
use better loading patterns to keep
bundle their users happy and optimize
cache loading performance!
main Yes !
bundle NOT SURE IF INTERNETS SLOW
emoji-picker
OR WEBSITE NOT WORKING
Type a message.
In many cases, we know that users will request certain resources soon after
the initial render of a page. Although they may not visible instantly, thus
shouldn't be included in the initial bundle, it would be great to reduce the
loading time as much as possible to give a better user experience!
Components or resources that we know are likely to be used at some point in
the application can be prefetched. We can let Webpack know that certain
bundles need to be prefetched, by adding a magic comment to the import
After building the application, we can see that the EmojiPicker will be
prefetched.
The actual output is visible as a link tag with rel="prefetch" in the head of our
document.
Modules that are prefetched are requested and loaded by the browser
even before the user requested the resource. When the browser is idle and
calculates that it's got enough bandwidth, it will make a request in order to
load the resource, and cache it. Having the resource cached can reduce the
loading time significantly, as we don't have to wait for the request to finish
after the user has clicked the button. It can simply get the loaded resource
from cache.
Although prefetching is a great way to optimize the loading time, don't overdo
it. If the user ended up never requesting the EmojiPicker component, we
unnecessarily loaded the resource. This could potentially cost a user money,
or slow down the application. Only prefetch the necessary resources.
Optimize list performance with list virtualization
In this guide, we will discuss list virtualization (also known as windowing). This
is the idea of rendering only visible rows of content in a dynamic list instead of
the entire list. The rows rendered are only a small subset of the full list with
what is visible (the window) moving as the user scrolls. This can improve
rendering performance.
If you use React and need to display large lists of data efficiently, you may be
familiar with react-virtualized. It's a windowing library by Brian Vaughn that
renders only the items currently visible in a list (within a scrolling "viewport").
This means you don't need to pay the cost of thousands of rows of data being
rendered at once. A video walkthrough of list virtualization with react-window
accompanies this write-up.
• Having a small container DOM element (e.g <ul>) with relative positioning
(window)
Rather than rendering 1000s of elements from a list at once (which can cause
slower initial rendering or impact scroll performance), virtualization focuses on
rendering just items visible to the user.
This can help keep list rendering fast on mid to low-end devices. You can
fetch/display more items as the user scrolls, unloading previous entries and
replacing them with new ones.
The APIs for both packages are similar and where they differ, react-window
tends to be simpler. react-window's components include:
List
Lists render a windowed list (row) of elements meaning that only the visible
rows are displayed to users (e.g FixedSizeList, VariableSizeList).
Lists use a Grid (internally) to render rows, relaying props to that inner Grid.
Row
Row
Row
Row
Row
Row
Not Rendered
Not Rendered
Rendering a list of data using React
Here's an example of rendering a list of simple data (itemsArray) using
React:
Rendering a list using react-window
If we wanted to render the same list as earlier with a grid layout, assuming our
input is a multi-dimensional array, we could accomplish this
using FixedSizeGrid as follows:
import React from ' react ' ;
import ReactDOM from ' react - dom ' ;
import { FixedSizeGrid as Grid } from ' react -window ' ;
const itemsArray [
[ { } , { } , { } , ... ) ,
[ { } , { } , { } , ... ) ,
[ { } , { }- , { } , ... ) ,
3
[ { } , { } , { } , ... ) ,
];
<div
className={
columnIndex % 2
? rowIndex % 2 0
{ Cell }
< / Grid >
);
react-window does not yet have the complete API surface of react
virtualized, so do check the comparison docs if considering it. What's
missing?
That said, we found react-window sufficient for most of our needs with what it
includes out of the box.
For rendering lists of dynamic content, I still recommend using a library like
react-window. It would be hard to have a
content-visbility: hidden version of such a library that beats a
version aggressively using display: none or removing DOM nodes when
Patterns are time-tested templates for writing code. They can be really
powerful, whether you're a seasoned developer or beginner, bringing a
valuable level of resilience and flexibility to your codebase.
Keep in mind that patterns are not a silver bullet. Take advantage of them
when you have a practical need to solve a problem and when you can use
them to write better code. Otherwise, be careful to avoid applying patterns
arbitrarily. If a problem you're attempting to solve is just hypothetical, maybe
it's premature to consider a pattern.
Always keep simplicity in mind. We try to when evaluating these ideas for the
apps we write and hope you will too. Ultimately what works best is often a
balance of trade-offs.
Understand if a pattern is helping you achieve your goals; whether it's better
user-experience, developer-experience or just smarter architecture. When you
have a seasoned knowledge of patterns, you'll appreciate when it may be a
good time to use one. Otherwise, study patterns and explore if they may be a
good fit for the problem you're attempting to solve. Once you've picked a
pattern, make sure you're evaluating the trade-offs of using it. If it looks
reasonable, you can use it.
Feel free to share "Learning Patterns" with your friends and colleagues. The
book is freely available at Patterns.dev and we welcome any feedback you
have. Until next time, so long and good luck, friends!