0% found this document useful (0 votes)
2 views32 pages

React JS Update V2

ReactJS is an open-source front-end JavaScript library developed by Facebook for building user interfaces, particularly single-page applications. It features components, a virtual DOM for performance, and the ability to create reusable UI elements, making it popular among developers. While it has advantages like speed and modularity, it also has drawbacks such as a steep learning curve due to JSX and larger file sizes.

Uploaded by

venkat Mohan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views32 pages

React JS Update V2

ReactJS is an open-source front-end JavaScript library developed by Facebook for building user interfaces, particularly single-page applications. It features components, a virtual DOM for performance, and the ability to create reusable UI elements, making it popular among developers. While it has advantages like speed and modularity, it also has drawbacks such as a steep learning curve due to JSX and larger file sizes.

Uploaded by

venkat Mohan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 32

What is ReactJS?

ReactJS is an open-source front-end JavaScript library for building user


interfaces. ReactJS is maintained by Facebook and a community of individual
developers and companies. It is widely used as a base in building single-page
websites and mobile applications. It is very easy to use, and it allows users to
create reusable UI components.

Features of ReactJS
JSX : JSX is an extension to javascript. Though it is not mandatory to use JSX in
react, it is one of the good features and easy to use.
Components: Components are like pure javascript functions that help make the
code easy by splitting the logic into reusable independent code. We can use
components as functions and components as classes. Components also have a
state, props which makes life easy. Inside a class, the state of each of the props
is maintained.
Virtual DOM: React creates a virtual dom, i.e., in-memory data -structure cache.
Only the final changes of DOM has later updated in the browsers DOM.
Javascript Expressions: JS expressions can be used in the jsx files using curly
brackets, for example {}.

Advantages of ReactJS
 ReactJS uses virtual dom that makes use of in-memory data-structure
cache, and only the final changes are updated in browsers dom. This
makes the app faster.
 You can create components of your choice by using the react component
feature. The components can be reused and also helpful in code
maintenance.
 Reactjs is an open-source javascript library, so it is easy to start with.
 ReactJS has become very popular in a short span and maintained by
Facebook and Instagram. It is used by many famous companies like
Apple, Netflix, etc.
 Facebook maintains ReactJS, the library, so it is well maintained and kept
updated.
 ReactJS can be used to develop rich UI for both desktop and mobile apps.
 Easy to debug and test as most of the coding is done in Javascript rather
than on Html.
Disadvantages of ReactJS
Here, are cons/ drawbacks of using ReactJS:
 Most of the code is written in JSX, i.e., Html and css are part of javascript,
it can be quite confusing as most other frameworks prefer keeping Html
separate from the javascript code.
 The file size of ReactJS is large.

Why do people choose to program with React?


There are various reasons why you should choose ReactJS as a primary tool for
website UI development. Here, we highlight the most notable ones and explain
why these specifics are so important:

 Fast - Feel quick and responsive through the Apps made in React can
handle complex updates.
 Modular - Allow you to write many smaller, reusable files instead of
writing large, dense files of code. The modularity of React is an attractive
solution for JavaScript's visibility issues.
 Scalable - React performs best in the case of large programs that display
a lot of data changes.
 Flexible - React approaches differently by breaking them into
components while building user interfaces. This is incredibly important in
large applications.
 Popular - ReactJS gives better performance than other JavaScript
languages due to t’s implementation of a virtual DOM.
 Easy to learn - Since it requires minimal understanding of HTML and
JavaScript, the learning curve is low.
 Server-side rendering and SEO friendly - ReactJS websites are famous
for their server-side rendering feature. It makes apps faster and much
better for search engine ranking in comparison to products with client-
side rendering. React even produces more opportunities for website SEO
and can occupy higher positions on the search result’s page.
 Reusable UI components - React improves development and debugging
processes.
 Community - The number of tools and extensions available for ReactJS
developers is tremendous. Along with impressive out-of-box
functionalities, more opportunities emerge once you discover how giant
the React galaxy is. React has a vibrant community and is supported by
Facebook. Hence, it’s a reliable tool for website development.
Create your First React Application

Prerequisite
Open Command Prompt, check the node and npm version
node –-version
npm –-version

Create a folder in our drive (ReactPractice)

Open Visual Studio code and open the folder (ReactPractice)

Open New Terminal inside the Visual Studio code and type the following
command to create your first React project.

Congrats! Your first react app was successfully created.

File Structure
node_modules: This folder contains all the dependencies and sub-
dependencies of packages used by the current React app.
public: This folder contains static assets of the web application. index.html
provides the entry point for the web app.
src: This folder contains JavaScript that will be processed by webpack. It's the
place where all your React-related source code lives. You'll work primarily in this
folder to develop your app.
.gitignore: A text file that tells the source control tool git which files or folders
to ignore in a project.
package.json: Primarily used to store the metadata associated with the project
as well as to store the list of dependency packages.
package-lock.json: According to the npm Docs, package-lock.json is
automatically generated for any operations where npm modifies either the
node_modules tree or package.json. It describes the exact tree that was
generated—subsequent installs can generate identical trees regardless of
intermediate dependency updates.
README.md: This file contains the basic information to get started with Create
React App.

Running the Development Web Server (Practice 2_1)

In the terminal redirect to the directory where the first react app is created

You can start the development web server by executing the following command
in the terminal:
In the browser you will see the output as shown below,

How the React application works


Or

It leads to warning.
Practice 2_2 (my-second-react-app)

Output:
React State
 React components has a built-in state object.
 The state object is where you store property values that belong to the
component.
 When the state object changes, the component re-renders.
 State of a React component is an object that contains information.
 State object stores values of the properties related to component.
 Hence whenever there is change in the properties related to component, the
value associated with the state object changes and the component will be
re-rendered.
 State can be used only in class components (later we will look into class and
functional components in detail with example) and state is generally
updated by event handlers.
ReactJS Props:
 Props in ReactJS are used to send data to components.
 Props are immutable, its values cannot be modified by a component that is
receiving it from outside.
 Props are used either in state or functional components.
 Props are used to pass data between parent and child components.

State Example 1
import React, { Component } from 'react'
export default class App extends Component {
constructor(){
super()
this.state={city:"Salem", pincode: 636005}
}
render() {
return (
<div>
<h1>Main Component</h1>
<h2>My City is {this.state.city}</h2>
<h2>Pincode {this.state.pincode}</h2>
</div>
)
}
}
State Example 2
import React, { Component } from 'react'

export default class App extends Component {


constructor(){
super()
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
<button
type="button"
onClick={this.changeColor}
>Change color</button>
</div>
)
}
}
Props Example 1
import React, { Component } from 'react'
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}!</h1>
);
}
}
export default class App extends Component {
render() {
return (
<div>
<Greeting name="John" />
<Greeting name="Jane" />
</div>
);
}
}

Example 6
import React, { Component } from 'react'
class MyComponent extends React.Component {
render() {
return (
// Accessing the prop 'name' passed to this component
<h1>Hello, {this.props.name}!</h1>
);
}
}
export default class App extends Component {
constructor(props) {
super(props);
// Initialize state to manage the prop value
this.state = {
name: 'John'
};
}

// Function to handle button click and update the state


handleClick = () => {
// Update the 'name' state value
this.setState({ name: 'Jane' });
};
render() {
return (
<div>
{/* Render MyComponent with the current state value of 'name' */}
<MyComponent name={this.state.name} />
{/* Button to update the 'name' value */}
<button onClick={this.handleClick}>Change Name</button>
</div>
);
}
}
React ES6

 ECMA Script 6 Version


 Write Less and DO More (Important feature of ES6)
 Class, Arrow Functions, Variables (let, const, var)

Class (index.js)
class Demo{
methodone(){
var a = 5;
var b = 10;
var c = a+b;
document.getElementById("root").innerHTML = c;
}
}
var myDemo = new Demo();
myDemo.methodone();
or
var a = function(){
var a = 5;
var b = 10;
var c = a+b;
document.getElementById("root").innerHTML = c;
}
a();
or
var a = () =>{
var a = 5;
var b = 10;
var c = a+b;
document.getElementById("root").innerHTML = c;
}
a();
or
var a = (x) =>{
var a = 5;
var b = 10;
var c = a+b+x;
document.getElementById("root").innerHTML = c;
}
a(20);
Use of let
var n = (x) =>{
var a = 5;
if (a===5){
let a = 10;
document.getElementById("root").innerHTML = a;
}
}
n(20);
The above program outputs 10 because a was local to the functions (let)
var n = (x) =>{
var a = 5;
if (a===5){
let a = 10;
}
document.getElementById("root").innerHTML = a;
}
n(20);
The above program outputs 5 because a was global to the functions (var)
React JSX
 JSX – Javascript XML
 Use to write HTML in React
 Use to write HTML elements in JS and place them in the DOM without any
createElement()
Example (with createElement) – index.js
const myele = React.createElement("h1",{},"Hello World");
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(myele);
You can see the output in the browser as Hello World
Example (without createElement) – index.js (Use of JSX)
const myele = <h1>Hello World!!!</h1>;
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(myele);
You can see the output in the browser as Hello World!!!
Example – add CSS and HTML together using JSX – index.js
var myStyle = {
color: "red",
textAlign: "center"
}
const myele = <div style={myStyle}>
<h1>Welocome</h1>
<h2>React Project</h2>
<p>R u there?</p>
</div>
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(myele);

Output

In the above example, we can also add expression within the HTML tags as shown
below

Example – add external CSS and HTML together using JSX – index.js
import './index.css';
const myele = <div>
<h1 className='header'>Welocome {5+10}</h1>
<h2>React Project</h2>
<p>R u there?</p>
</div>
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(myele);

index.css
.header{
color:blueviolet;
text-align: center;
}
Output
React Components

 A React component takes an optional input and returns a React element


which is rendered on the screen.
 functional components accept data, or more technically, it takes props as a
function argument and returns the data in valid JSX form.
 A React component can be either “stateful” or “stateless.”
 “Stateful” components are of the class type, while “stateless” components
are of the function type.

Example – function component (index.js)

function Header(){
return <div>
<h1>Sona College of Technology</h1>
<h2>logo</h2>
</div>
}
function Sidebar(){
return <h1>Sidebar</h1>
}
function Navbar(){
return <h1>Navbar</h1>
}
function MyWebsite(){
return <div>
<Header/>
<Sidebar/>
<Navbar/>
</div>
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyWebsite/>);

Pre-requisites:

 Must have an uppercase first letter.


 Must return JSX.
Example – function component

App.js

const Video = (props) => {


return <h1> Video Component - {10+20}</h1>
}
export default Video;
index.js

import Video from './App';


const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Video/>);

 Above is the example for a react functional component props as an


argument and returns the support in the valid JSX form.
 In real-world applications, passing the props to the functional components
is expected. Props are an integral part of every react application. It gives
information from one component to another, which helps us build dynamic
and robust applications.
 One thing to note here is that props are read-only, which means that the
React components need not change their values and that the same props
return the same value. The components which follow this pattern are called
Pure components, and in other words, functional components are pure
components.
Example
App.js
import React from 'react'
function Greeting() {
return ('h1', {id: 'greeting', className: 'hello'}, 'Hello, World!');
}
const App = () => {
return (
<Greeting/>
)
}
export default App

with props (App.js)


import React from 'react'
function Greeting(props) {
return ('h1', {id: 'greeting', className: 'hello'}, `Hello, $
{props.name}!`);
}
const App = () => {
return (
<Greeting name = "Sona"/>
)
}
export default App

Creating More Complicated Components

In real life, you will have to create much more complicated layouts, and using the
above method for creating components will no longer be feasible.
The following example creates another component that will demonstrate how
cumbersome it can get to create complicated components with multiple children.
App.css
div.container {
margin: 6rem auto;
width: fit-content;
font-size: 3rem;
text-align: center;
}
h2 {
margin: 1rem;
font-family: "Bebas Neue";
}
p {
margin: 1rem;
font-family: "Asap Condensed";
font-weight: 400;
}
App.js
import React from 'react'
import './App.css'
function Country(props) {
return React.createElement(
'div', {
className: "container"
}, React.createElement(
'h2', {
className: "country-name"
}, `Country Name: ${props.name}`),
React.createElement('p', {
className: "capital"
}, `Capital: ${props.capital}`),
React.createElement('p', {
className: "population"
}, `Population: ${props.population}`));
}
const App = () => {
return (
<Country name= 'United States' capital= 'Washington, D.C.' population
='332 million'/>
)
}
export default App

ES6 class component (Uses ES6 class)

The core difference between function and class component are −

 Function components are very minimal in nature. Its only requirement is to


return a React element.
class <classname> extends React.Component {
render() {
return (
<div>Hello</div>
);
}
}
 Class components supports state management out of the box whereas
function components does not support state management. But, React
provides a hook, useState() for the function components to maintain its
state.
 Class component have a life cycle and access to each life cycle events
through dedicated callback apis. Function component does not have life
cycle. Again, React provides a hook, useEffect() for the function component
to access different stages of the component.
Example class component

Create a folder <Components> in src directory


Inside the Components folder create a js file <ExpenseEntryItem.js>
Create a class as specified below:
import React from 'react'
class ExpenseEntryItem extends React.Component {
render() {
return (
<div>
<div><b>Item:</b> <em>Mango Juice</em></div>
<div><b>Amount:</b> <em>30.00</em></div>
<div><b>Spend Date:</b> <em>2020-10-10</em></div>
<div><b>Category:</b> <em>Food</em></div>
</div>
)
}
}
export default ExpenseEntryItem
index.js

import ExpenseEntryItem from './components/ExpenseEntryItem';


const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<ExpenseEntryItem/>);
Output
React class based components are the bread and butter of most modern web apps
built in ReactJS. These components are simple classes (made up of multiple
functions that add functionality to the application). All class based components are
child classes for the Component class of ReactJS.
Example: Program to demonstrate the creation of class-based components. Create
a React app and edit the App.js as:

import React, { Component } from 'react'


export default class App extends Component {
render() {
return <h1>Sona College of Technology</h1>;
}
}
Once a component is declared, it can be used in other components. Program to
demonstrate the use of class-based components in other components.

import React, { Component } from 'react'


class Sample extends React.Component {
render() {
return <h1>A Computer Science Portal For Sona</h1>;
}
}
export default class App extends Component {
render() {
return <Sample/>;
}
}
The main feature of class-based components that distinguished them from
functional components is that they have access to a state which dictates the
current behavior and appearance of the component (Later, with React Hooks
introduced in version 16.8, we are able to declare a stateful component without
declaring a class). This state can be modified by calling the setState() function. One
or more variables, arrays, or objects defined as part of the state can be modified at
a time with the setState() function.

Example: Program to demonstrate the use of state in class-based components.


Open the App.js file and replace the code with the below code.

import React, { Component } from 'react'


export default class App extends Component {
constructor(props) {
super(props);
this.state = { change: true };
}
render() {
return (
<div>
<button
onClick={() => {
this.setState({ change: !this.state.change });
}}
>
Click Here!
</button>
{this.state.change ? (
<h1>Welcome to Sona College of Technology</h1>
) : (
<h1>A Computer Science Portal for Sona</h1>
)}
</div>
)
}
}
Functional Components vs Class Components:
Functional Components Class Components
A functional component is just a plain
A class component requires you to extend
JavaScript pure function that accepts props
from React. Component and create a render
as an argument and returns a React
function which returns a React element.
element(JSX).
It must have the render() method returning
There is no render method used in
JSX (which is syntactically similar to
functional components.
HTML)
Class component is instantiated and
Functional component run from top to
different life cycle method is kept alive and
bottom and once the function is returned it
being run and invoked depending on phase
cant be kept alive.
of class component.
Also known as Stateless components as they
simply accept data and display them in some Also known as Stateful components
form, that they are mainly responsible for because they implement logic and state.
rendering UI.
React lifecycle methods (for example, React lifecycle methods can be used inside
componentDidMount) cannot be used in class components (for example,
functional components. componentDidMount).
Hooks can be easily used in functional It requires different syntax inside a class
components to make them Stateful. component to implement hooks.
example: const [name,SetName]=
example: constructor(props) {
React.useState(‘ ‘)
super(props);
this.state = {name: ‘ ‘}
}
Constructor are used as it needs to store
Constructors are not used.
state.

Composing Component

 Component composition is a powerful pattern to make your components


more reusable.
 In React, we can make components more generic by accepting props, which
are to React components what parameters are to functions.
 Component composition is the name for passing components as props to other
components, thus creating new components with other components.

import React from 'react'


const Button = ({ onClick, children }) => (
<button onClick={onClick}>{children}</button>
);
const App = () => {
const onClick = () => alert('Hey ���');
return (
<Button onClick={onClick}>Click me!</Button>
);
}
export default App
children is nothing more than a prop to the Button component.
Instead of passing down a string to Button, we may want to add an icon to the text as
well:
import React from 'react'
const Button = ({ onClick, children }) => (
<button onClick={onClick}>{children}</button>
);
const App = () => {
const onClick = () => alert('Hey ���');

return (
<Button onClick={onClick}>
<img src="/logos/logo.svg" alt='logo'/>
Click me!
</Button>
);
}
export default App
But we're not limited to the children prop. We can create more specific props that
can accept components as well:
import React from 'react'
const Button = ({ onClick, icon, children }) => (
<button onClick={onClick}>{icon}{children}</button>
);
const App = () => {
const onClick = () => alert('Hey ���');
return (
<Button onClick={onClick}>
<img src="/logos/logo.svg" alt='logo'/>
Click me!
</Button>
);
}
export default App
And that is the essence of component composition: a simple yet incredibly
powerful pattern that makes React components highly reusable.
When working on React projects, you'll continuously find yourself refactoring
components to be more generic through component composition so that you can
use them in multiple places.
import React from 'react'
const WelcomePage = ({ userName }) => {
return (
<>
<WelcomeMessage userName={userName} />
{/** Some other welcome page code */}
</>
);
}
const WelcomeMessage = ({ userName }) => {
return (
<h1>Hey, {userName}!</h1>
);
}
const App = () => {
const userName = 'Joe';
return (
<WelcomePage userName={userName} />
);
}
export default App
Here's a visualization of how the components are structured:

App passes userName to WelcomePage, and WelcomePage passes userName to


WelcomeMessage.
With only a few layers, this isn't a big deal, but this can quickly get out of hand in
larger applications.
The easiest solution? Component composition!
Instead of passing userName through all these layers, we can try to compose the
components at a higher level, like the App component.
import React from 'react'
const WelcomePage = ({ title }) => {
return (
<>
{title}
{/** Some other welcome page code */}
</>
);
}
const WelcomeMessage = ({ userName }) => {
return (
<h1>Hey, {userName}!</h1>
);
}
const App = () => {
const userName = 'Joe';
return (
<WelcomePage title={<WelcomeMessage userName={userName} />} />
);
}
export default App
We can now see that only App imports all the components. We successfully removed
one layer and avoided prop drilling.

Our app, after removing one layer with component composition. We don't need to
pass down userName twice anymore—we just pass it to WelcomeMessage right
away.
Now, I don't say that either of these examples is bad code and that prop drilling
should be avoided at all costs.
However, it's a useful pattern to be aware of if prop-drilling becomes an issue.

How can composition help performance?


Composition is also a great ally if you try to reduce the number of re-renders in
your application.
Let's say you have a Post component that displays the scroll progress. It updates
the state base on the scroll event:
App.js

import React from 'react'


import "./App.css"
const RenderCounter = () => {
const rerenderCounter = React.useRef(0);
rerenderCounter.current += 1;
console.log(rerenderCounter.current);
return <></>;
}
const Post = () => {
const [progress, setProgress] = React.useState(0);
React.useEffect(() => {
const scrollListener = () => {
// update the progress based on the scroll position
const newPercentage = Math.floor(document.documentElement.scrollTop
/ (document.documentElement.scrollHeight -
document.documentElement.clientHeight) * 100);
if (newPercentage !== progress) {
setProgress(newPercentage);
}
}
window.addEventListener('scroll', scrollListener, false);
})
return (
<>
<h2 className="progress">
Progress: {progress}%
</h2>
<div className="content">
<h1>Content Title</h1>
<RenderCounter/>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
{/** more content */}
</div>
</>
)
}
const App = () => {
return (
<Post/>
);
}
export default App
App.css

body {
font-family: Sans-serif;
height: 300vh;
}

.progress {
top: 10px;
left: 10px;
position: fixed;
background-color: white;
padding: 5px;
border-radius: 5px;
}

.content {
margin-top: 70px;
}
This code will cause a lot of re-renders, and we can assume that the blog post
content contains a lot more components—so re-renders will be expensive.
If we move the logic to a separate component and use component composition to
glue them together, the number of re-renders goes from 61 (on my computer) to 1 for the
content section of the Post component.
All I did was moving the state updates to PostLayout and rendering the post
content as a prop.
App.js

import React, {useEffect} from 'react'


import "./App.css"
const PostLayout = ({ children }) => {
const [progress, setProgress] = React.useState(0);
useEffect(() => {
const scrollListener = () => {
const newPercentage = Math.floor(document.documentElement.scrollTop
/ (document.documentElement.scrollHeight -
document.documentElement.clientHeight) * 100);
if (newPercentage !== progress) {
setProgress(newPercentage);
}
}
window.addEventListener('scroll', scrollListener, false);
});
return (
<>
<h2 className="progress">
Progress: {progress}%
</h2>
{children}
</>
);
}
const RenderCounter = () => {
const rerenderCounter = React.useRef(0);
rerenderCounter.current += 1;
console.log(rerenderCounter.current);
return <></>;
}

const Post = () => {


return (
<PostLayout>
<div className="content">
<h1>Content</h1>
<RenderCounter />
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
</div>
</PostLayout>
)
}
const App = () => {
return (
<Post/>
);
}
export default App
App.css is similar to previous example

Why is it that the content only renders once in this case?


The reason is that React renders props only if they change.

You might also like