0% found this document useful (0 votes)
82 views

React Components

The document discusses code splitting in React, which allows splitting code bundles that can be dynamically loaded at runtime. This helps make websites and applications with large or deep component trees lighter. Code splitting allows lazy loading parts of the code only when needed. It can be implemented using dynamic imports and bundled using tools like Webpack. React.lazy and Suspense allow defining components for lazy loading and showing loading states. Code splitting helps improve performance by reducing bundle size and loading only required code.

Uploaded by

Buvana Siva
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

React Components

The document discusses code splitting in React, which allows splitting code bundles that can be dynamically loaded at runtime. This helps make websites and applications with large or deep component trees lighter. Code splitting allows lazy loading parts of the code only when needed. It can be implemented using dynamic imports and bundled using tools like Webpack. React.lazy and Suspense allow defining components for lazy loading and showing loading states. Code splitting helps improve performance by reducing bundle size and loading only required code.

Uploaded by

Buvana Siva
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Code Splitting in React




Code-Splitting is a feature supported by bundlers like Webpack, Rollup, and
Browserify which can create multiple bundles that can be dynamically loaded at
runtime.
As websites grow larger and go deeper into components, it becomes heavier. This is
especially the case when libraries from third parties are included. Code Splitting is a
method that helps to generate bundles that are able to run dynamically. It also helps to
make the code efficient because the bundle contains all required imports and files.
Bundling and its efficiency: Bundling is the method of combining imported files
with a single file. It is done with the help of Webpack, Rollup, and Browserify as
they can create many bundles that can be loaded dynamically at runtime.
With the help of code splitting, ‘lazy load’ can be implemented, which means just
using the code which is currently needed.
 The default way of importing is as follows:
import { add } from './math';

console.log(add(x, y)); // Here x, y are two numbers


 Using code-splitting this can be done as follows:
import("./math").then(math => {
console.log(math.add(x, y));
});
// Here x, y are two numbers
As soon as Webpack gets this type of syntax, code-splitting is started automatically.
When using the Create React App, it is already set up and can be used immediately.
The Webpack guide on code splitting should be followed if using Webpack. The
instructions can be found here.
When Babel is being used, it has to be made sure that Babel is not transforming the
import syntax, but can parse it dynamically. This can be done using babel-plugin-
syntax-dynamic-import.
React.lazy and Suspense
As both React.lazy and Suspense are not available for rendering on the server yet now,
it is recommended to use loadable-components for code-splitting in a server-rendered
app. React.lazy is helpful for rendering dynamic import as a regular component.
Before:
import Component from './Component';
After:
const Component = React.lazy(() => import('./Component'));
The Bundle will be loaded on its own which contains the Component when this
component is rendered first.
The Lazy component should then be rendered inside Suspense Component which
helps to reflect some fallback content meanwhile the lazy component loads.

 Javascript

import React, { Suspense } from 'react';


const Component = React.lazy(() => import('./Component'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
</div>);
}

The fallback prop can accept any element of React which will be rendered while
waiting for the loading of the Component. The Suspense Component can be placed
anywhere above the lazy component. Moreover, multiple lazy components can be
wrapped with a single Suspense Component.

 Javascript

import React, { Suspense } from 'react';

const ComponentOne =
React.lazy(() => import('./ComponentOne'));
const ComponentTwo =
React.lazy(() => import('./ComponentTwo'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
</div>);
}

Error Boundaries
Error Boundaries are React components that help when some modules fail to load due
to any issue, an error will be triggered. These errors can be handled properly and
provide a good experience to the user by the use of a suitable error page.
 Javascript

import React, { Suspense } from 'react';


import ErrorBoundary from './ErrorBoundary';
const ComponentOne = React.lazy(() =>
import('./ComponentOne'));
const ComponentTwo = React.lazy(() =>
import('./ComponentTwo'));
const MyComponent = () => (
<div>
<Suspense fallback={<div>Loading...</div>}>
</div>
);

Route-Based Code Splitting


It can be difficult to implement code-splitting in code, the bundles can be split evenly,
which will improve the experience for the user.
Here you can see the example code for this.

 Javascript

import React,{Suspense, lazy} from 'react';


import {Route, Switch, BrowserRouter } from 'react-router-dom';

const HomePage = lazy(() =>


import('./routes/HomePage'));
const AboutUs = lazy(() =>
import('./routes/AboutUs'));
const App = () =>
(<Suspense fallback={<div>Loading...</div>}>);

Named Exports

React.lazy currently supports only default exports. An intermediate module that re-
exports as default has to be created if one wants to import a module that uses named
exports. This ensures the working of tree shaking and prevents the pulling in of
unused components.

 Javascript

import {React, lazy} from 'react';

// Components.js
export const Component = /* ... */;
export const MyUnusedComponent = /* ... */;

// Component.js
export { Component as default } from "./Components.js";
// MyApp.js
const Component = lazy(() => import("./Component.js"));

What is a ReactJS Component?


A Component is one of the core building blocks of React. In other words, we can
say that every application you will develop in React will be made up of pieces called
components. Components make the task of building UIs much easier. You can see a
UI broken down into multiple individual pieces called components and work on
them independently and merge them all in a parent component which will be your
final UI.
You can see in the below image we have broken down the UI of GeeksforGeeks’s
homepage into individual components.

Components in React basically return a piece of JSX code that tells what should be
rendered on the screen.
Types of components in ReactJS
In React, we mainly have two types of components:
Functional Components: Functional components are simply javascript functions.
We can create a functional component in React by writing a javascript function.
These functions may or may not receive data as parameters, we will discuss this later
in the tutorial. The below example shows a valid functional component in React:
function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}
Class Components: The class components are a little more complex than the
functional components. The functional components are not aware of the other
components in your program whereas the class components can work with each
other. We can pass data from one class component to another class component. We
can use JavaScript ES6 classes to create class-based components in React. The
below example shows a valid class-based component in React:
class Democomponent extends React.Component {
render() {
return <h1>Welcome Message!</h1>;
}
}

The components we created in the above two examples are equivalent, and we also
have stated the basic difference between a functional component and a class
component. We will learn about more properties of class-based components in
further tutorials.
For now, keep in mind that we will use functional components only when we are
sure that our component does not require interacting or work with any other
component. That is, these components do not require data from other components
however we can compose multiple functional components under a single functional
component.
We can also use class-based components for this purpose but it is not recommended
as using class-based components without need will make your application in-
efficient.
Rendering Components in ReactJS
React is also capable of rendering user-defined components. To render a component
in React we can initialize an element with a user-defined component and pass this
element as the first parameter to ReactDOM.render() or directly pass the component
as the first argument to the ReactDOM.render() method.
The below syntax shows how to initialize a component to an element:
const elementName = <ComponentName />;

In the above syntax, the ComponentName is the name of the user-defined


component.
Note: The name of a component should always start with a capital letter. This is
done to differentiate a component tag from HTML tags.
The below example renders a component named Welcome to the Screen:
Open your index.js file from your project directory, and make the given below
changes:
src index.js:
 javascript

import React from 'react';


import ReactDOM from 'react-dom';

// This is a functional component


const Welcome = () => {
return <h1>Hello World!</h1>
}

ReactDOM.render(
<Welcome />,
document.getElementById("root")
);

Output:

Let us see step-wise what is happening in the above example:


 We call the ReactDOM.render() as the first parameter.
 React then calls the component Welcome, which returns <h1>Hello
World!</h1>; as the result.
 Then the ReactDOM efficiently updates the DOM to match with the
returned element and renders that element to the DOM element with id as
“root”.
ReactJS | Components – Set 2
 Read
 Discuss
 Courses



In our previous article on ReactJS | Components we had to discuss components, types
of components, and how to render components. In this article, we will see some more
properties of components.

Composing Components: Remember in our previous article, our first example of


GeeksforGeeks’s homepage which we used to explain components? Let’s recall what
we have told, “we can merge all of these individual components to make a parent
component”. This is what we call composing components. We will now create
individual components named Navbar, Sidebar, ArticleList and merge them to create a
parent component named App and then render this App component.
The below code in the index.js file explains how to do this:
Filename- App.js:
 javascript

import React from 'react';


import ReactDOM from 'react-dom';

// Navbar Component
const Navbar=()=>
{
return <h1>This is Navbar.< /h1>
}

// Sidebar Component
const Sidebar=()=> {
return <h1>This is Sidebar.</h1>
}

// Article list Component


const ArticleList=()=>
{
return <h1>This is Articles List.</h1>
}

// App Component
const App=()=>
{
return(
<div>
<Navbar />
<Sidebar />
<ArticleList />
</div>
);
}

ReactDOM.render(
<App />,
document.getElementById("root")
);

Output:
You can see in the above output that everything worked well, and we managed to
merge all the components into a single component App.

Decomposing Components: Decomposing a Component means breaking down the


component into smaller components. We have told the thing about composing smaller
components to build a parent component from the very start when we started
discussing components repeatedly. Let us see why there is a need to do so. Suppose
we want to make a component for an HTML form. Let’s say our form will have two
input fields and a submit button. We can create a form component as shown below:
Filename- App.js:
 javascript

import React from 'react';


import ReactDOM from 'react-dom';

const Form=()=>
{
return (
<div>
<input type = "text" placeholder = "Enter Text.." />
<br />
<br />
<input type = "text" placeholder = "Enter Text.." />
<br />
<br />
<button type = "submit">Submit</button>
</div>
);
}

ReactDOM.render(
<Form />,
document.getElementById("root")
);

Output:
The above code works well to create a form. But let us say now we need some other
form with three input fields. To do this we will have to again write the complete code
with three input fields now. But what if we have broken down the Form component
into two smaller components, one for the input field and another one for the button?
This could have increased our code reusability to a great extent. That is why it is
recommended to React to break down a component into the smallest possible units
and then merge them to create a parent component to increase the code modularity and
reusability. In the below code the component Form is broken down into smaller
components Input and Button.
Filename- App.js:
 javascript

import React from 'react';


import ReactDOM from 'react-dom';

// Input field component


const Input=()=>
{
return(
<div>
<input type="text" placeholder="Enter Text.." />
<br />
<br />
</div>
);
}

// Button Component
const Button=()=>
{
return <button type = "submit">Submit</button>;
}

// Form component
const Form=()=>
{
return (
<div>
<Input />
<Input />
<Button />
</div>
);
}

ReactDOM.render(
<Form />,
document.getElementById("root")
);

Output:

Till now, we have worked with Components with only static data. That is, we are
writing data directly inside a Component. What if, we want to pass some data to our
Components? React allows us to do so with the help of another property called props.
ReactJS Pure Components



Generally, In ReactJS, we use shouldComponentUpdate() Lifecycle method to
customize the default behavior and implement it when the React component should re-
render or update itself.
Prerequisite:
 ReactJS Components
 ReactJS Components – Set 2

Now, ReactJS has provided us a Pure Component. If we extend a class with Pure
Component, there is no need for shouldComponentUpdate() Lifecycle
Method. ReactJS Pure Component Class compares current state and props with new
props and states to decide whether the React component should re-render itself
or Not.
In simple words, If the previous value of state or props and the new value of state or
props is the same, the component will not re-render itself. Since Pure
Components restricts the re-rendering when there is no use of re-rendering of the
component. Pure Components are Class Components which
extends React.PureComponent.
Example: Program to demonstrate the creation of Pure Components.
javascript

import React from ‘react’;

export default class Test extends React.PureComponent{

render(){

return <h1>Welcome to GeeksforGeeks</h1>;

Output :

Extending React Class Components with Pure Components ensures the higher
performance of the Component and ultimately makes your application faster, While in
the case of Regular Component, it will always re-render either value of State and
Props changes or not.
While using Pure Components, Things to be noted are that, In these components, the
Value of State and Props are Shallow Compared (Shallow Comparison) and It also
takes care of “shouldComponentUpdate” Lifecycle method implicitly.
So there is a possibility that if these State and Props Objects contain nested data
structure then Pure Component’s implemented shouldComponentUpdate will
return false and will not update the whole subtree of Children of this Class
Component. So in Pure Component, the nested data structure doesn’t work
properly.
In this case, State and Props Objects should be simple objects and Child Elements
should also be Pure, means to return the same output for the same input values at any
instance.
ReactJS Functional Components



In this article, we will learn about funcitonal components in React, different ways to
call the functional component and also learn how to create the functional components.
We will also demonstrate the use of hooks in functional components
Functional components in React
ReactJS Functional components are some of the more common components that
will come across while working in React. These are simply JavaScript functions. We
can create a functional component in React by writing a JavaScript function. These
functions may or may not receive data as parameters. In the functional Components,
the return value is the JSX code to render to the DOM tree.
Ways to call the functional component:
We can call the functions in javascript in other ways as follows:
1. Call the function by using the name of the function followed by the Parentheses.
// Example of Calling the function with function name followed by
Parentheses
import React from 'react';
import ReactDOM from 'react-dom/client';
function Parentheses() {
return (<h1>
We can call function using name of the
function followed by Parentheses
</h1>);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(Parentheses());
2. Call the function by using the functional component method.
// Example of Calling the function using component call
import React from 'react';
import ReactDOM from 'react-dom/client';
function Comp() {
return (<h1> As usual we can call the function using component
call</h1>);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Comp />);
Now, We will use the functional component method to create a program and see how
functional components render the component in the browser.
Program to demonstrate the creation of functional components
 Open your React project directory and go to the src folder then edit
the index.js file.
 Javascript
//index.js File

import React from 'react';

import ReactDOM from 'react-dom';

import Demo from './App';

ReactDOM.render(

<React.StrictMode>

<Demo />

</React.StrictMode>,

document.getElementById('root')

);

 Open the App.js file from the src folder and edit the file.
 Javascript
//App.js File

import React from 'react';

import ReactDOM from 'react-dom';

const Demo=()=>{return <h1>Welcome to GeeksforGeeks</h1>};

export default Demo;

Output: After editing both files check the output in the browser. You will get the
output as shown below.
Problem with using functional components
Functional components lack a significant amount of features as compared to class-
based components and they do not have access to dedicated state variables like class-
based components.
Advantage of using hooks in functional components
The problem discussed above is solved with the help of a special ReactJS concept
called “hooks”. ReactJS has access to a special hook
called useState(). The useState() is used to initialize only one state variable to
multiple state variables. The first value returned is the initial value of the state
variable, while the second value returned is a reference to the function that updates it.
Program to demonstrate the use of useState() hook
Filepath- src/index.js: Open your React project directory and edit the Index.js file
from the src folder.
 Javascript
//index.js File

import React from 'react';

import ReactDOM from 'react-dom';

import Example from './App';

ReactDOM.render(

<React.StrictMode>

<Example />

</React.StrictMode>,

document.getElementById('root')

);

Filepath- src/App.js: Open your React project directory and edit the App.js file from
the src folder:
 Javascript
//App.js File

import React, { useState } from 'react';

const Example = () => {

const [change, setChange] = useState(true);

return (

<div>

<button onClick={() => setChange(!change)}>

Click Here!

</button>

{change ? <h1>Welcome to GeeksforGeeks</h1> :

<h1>A Computer Science Portal for Geeks</h1>}

</div>

);

export default Example;

Output: You will get the output as shown below.

Functional components do not have access to lifecycle functions like class-based


components do since lifecycle functions need to be defined within the boundaries of a
class. A special React hook called useEffect() needs to be used. It is worth noting
that useEffect() isn’t an exact duplicate of the lifecycle functions – it works and
behaves in a slightly different manner.
Program to demonstrate the use of useEffect() hook
 Filepath- src/index.js: Open your React project directory and edit
the index.js file from the src folder.
 Javascript
//index.js File

import React from 'react';

import ReactDOM from 'react-dom';

import Example from './App';

ReactDOM.render(

<React.StrictMode>

<Example />

</React.StrictMode>,

document.getElementById('root')

);

 Filepath- src/App.js: Open your React project directory and edit


the App.js file from the src folder.
 Javascript
//App.js File

import React, { useEffect } from 'react';

const Example = () => {

useEffect(() => {

console.log("Mounting...");

});

return (

<h1>

Geeks....!

</h1>

);

export default Example;

Output: you will get the output like this in your browser.
Data is passed from the parent component to the child components in the form of
props. ReactJS does not allow a component to modify its own props as a rule. The
only way to modify the props is to change the props being passed to the child
component. This is generally done by passing a reference of a function in the parent
component to the child component.
Program to demonstrate the use of props
 Filepath- src/index.js: Open your React project directory and edit
the Index.js file from the src folder.
 Javascript
//index.js File

import React from 'react';

import ReactDOM from 'react-dom';

import Example from './App';

ReactDOM.render(

<React.StrictMode>

<Example />

</React.StrictMode>,

document.getElementById('root')

);

 Filepath- src/App.js: Open your React project directory and edit


the App.js file from the src folder.
 Javascript
import React, { useState } from 'react';

import props from 'prop-types';

const Example = () => {

return (

<h1>{props.data}</h1>

);

function propsExample() {

const [change, setChange] = useState(true);

return (

<div>

<button onClick={() => setChange(!change)}>

Click Here!

</button>

{change ?

<Example data="Welcome to GeeksforGeeks" /> :

<Example data="A Computer Science Portal for Geeks" />}

</div>

);

export default Example;

Output: You will see the output like this in your browser.

ReactJS Lifecycle of Components





The lifecycle of a component starts from its initialization and ends when it is
unmounted from the DOM. We will also discuss about each phase in brief.
Lifecycle of Components
Every React Component has a lifecycle of its own, lifecycle of a component can be
defined as the series of methods that are invoked in different stages of the
component’s existence. The definition is pretty straightforward but what do we mean
by different stages? A React Component can go through four stages of its life as
follows.
 Initialization: This is the stage where the component is constructed with
the given Props and default state. This is done in the constructor of a
Component Class.
 Mounting: Mounting is the stage of rendering the JSX returned by the
render method itself.
 Updating: Updating is the stage when the state of a component is updated
and the application is repainted.
 Unmounting: As the name suggests Unmounting is the final step of the
component lifecycle where the component is removed from the page.
React provides the developers with a set of predefined functions that if present are
invoked around specific events in the lifetime of the component. Developers are
supposed to override the functions with desired logic to execute accordingly. We have
illustrated the gist in the following diagram.

Now let us describe each phase and its corresponding functions.


Functions of each Phase of Lifecycle:
Initialization
In this phase, the developer has to define the props and initial state of the component
this is generally done in the constructor of the component. The following code snippet
describes the initialization process.
class Clock extends React.Component {
constructor(props)
{
// Calling the constructor of
// Parent Class React.Component
super(props);

// Setting the initial state


this.state = { date : new Date() };
}
}
Mounting
Mounting is the phase of the component lifecycle when the initialization of the
component is completed and the component is mounted on the DOM and rendered for
the first time on the webpage. Now React follows a default procedure in the Naming
Conventions of these predefined functions where the functions containing “Will”
represents before some specific phase and “Did” represents after the completion of
that phase. The mounting phase consists of two such predefined functions as described
below.
 First initialize the data and the states in the constructor
 componentDidMount() Function: This function is invoked right after the
component is mounted on the DOM i.e. this function gets invoked once
after the render() function is executed for the first time
Updation
React is a JS library that helps create Active web pages easily. Now active web pages
are specific pages that behave according to their user. For example, let’s take the
GeeksforGeeks {IDE} webpage, the webpage acts differently with each user. User A
might write some code in C in the Light Theme while another User may write Python
code in the Dark Theme all at the same time. This dynamic behavior that partially
depends upon the user itself makes the webpage an Active webpage. Now how can
this be related to Updation? Updation is the phase where the states and props of a
component are updated followed by some user events such as clicking, pressing a key
on the keyboard, etc. The following are the descriptions of functions that are invoked
at different points of the Updation phase.
 getDerivedStateFromProps: getDerivedStateFromProps(props, state) is a
static method that is called just before render() method in both mounting
and updating phase in React. It takes updated props and the current state as
arguments.
static getDerivedStateFromProps(props, state) {
if(props.name !== state.name){
//Change in props
return{
name: props.name
};
}
return null; // No change to state
}
 setState() Function: This is not particularly a Lifecycle function and can be
invoked explicitly at any instant. This function is used to update the state of
a component. You may refer to this article for detailed information.
 shouldComponentUpdate() Function: By default, every state or props
update re-renders the page but this may not always be the desired outcome,
sometimes it is desired that updating the page will not be repainted. The
shouldComponentUpdate() Function fulfills the requirement by letting
React know whether the component’s output will be affected by the update
or not. shouldComponentUpdate() is invoked before rendering an already
mounted component when new props or states are being received. If
returned false then the subsequent steps of rendering will not be carried out.
This function can’t be used in the case of forceUpdate(). The Function takes
the new Props and new State as the arguments and returns whether to re-
render or not.
 getSnapshotBeforeUpdate() Method: The getSnapshotBeforeUpdate()
method is invoked just before the DOM is being rendered. It is used to store
the previous values of the state after the DOM is updated.
 componentDidUpdate() Function: Similarly this function is invoked after
the component is rerendered i.e. this function gets invoked once after the
render() function is executed after the updation of State or Props.
Unmounting
This is the final phase of the lifecycle of the component which is the phase of
unmounting the component from the DOM. The following function is the sole
member of this phase.
 componentWillUnmount() Function: This function is invoked before the
component is finally unmounted from the DOM i.e. this function gets
invoked once before the component is removed from the page and this
denotes the end of the lifecycle.
We have so far discussed every predefined function there was in the lifecycle of the
component, and we have also specified the order of execution of the function.
Implementing the lifecycle methods
Let us now see one final example to finish the article while revising what’s discussed
above.
First, create a react app and edit your index.js file from the src folder.
src index.js:
Javascript

import React from 'react';

import ReactDOM from 'react-dom/client';

class Test extends React.Component {

constructor(props) {

super(props);

this.state = { hello: "World!" };

}
componentDidMount() {

console.log("componentDidMount()");

changeState() {

this.setState({ hello: "Geek!" });

render() {

return (

<div>

<h1>GeeksForGeeks.org, Hello{this.state.hello}</h1>

<h2>

<a onClick={this.changeState.bind(this)}>Press Here!</a>

</h2>

</div>);

shouldComponentUpdate(nextProps, nextState) {

console.log("shouldComponentUpdate()");

return true;

componentDidUpdate() {

console.log("componentDidUpdate()");

const root = ReactDOM.createRoot(document.getElementById("root"));


root.render(

<Test />

);

Output:
Differences between Functional Components and Class
Components



In this article, we will learn about the differences between functional and class
components in React with the help of an example. We will create a counter and
implement it using both class and functional components to understand the differences
practically.
Functional Components
Functional components are some of the more common components that will come
across while working in React. These are simply JavaScript functions. We can create a
functional component to React by writing a JavaScript function.
Syntax:
const Car=()=> {
return <h2>Hi, I am also a Car!</h2>;
}
Counter using Functional Components
Example:
 Javascript

import React, { useState } from "react";

const FunctionalComponent = () => {


const [count, setCount] = useState(0);

const increase = () => {


setCount(count + 1);
}
return (
<div style={{ margin: '50px' }}>
<h1>Welcome to Geeks for Geeks </h1>
<h3>Counter App using Functional Component : </h3>
<h2>{count}</h2>
<button onClick={increase}>Add</button>
</div>
)
}

export default FunctionalComponent;

Output:

Class Component
This is 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).
Syntax:
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Counter using Class Components
Example:
 Javascript
import React, { Component } from "react";

class ClassComponent extends React.Component {


constructor() {
super();
this.state = {
count: 0
};
this.increase = this.increase.bind(this);
}

increase() {
this.setState({ count: this.state.count + 1 });
}

render() {
return (
<div style={{ margin: '50px' }}>
<h1>Welcome to Geeks for Geeks </h1>
<h3>Counter App using Class Component :
</h3>
<h2> {this.state.count}</h2>
<button onClick={this.increase}>
Add</button>

</div>
)
}
}

export default ClassComponent;

Output:
In the above example, for functional components, we use hooks (useState) to manage
the state. If you write a function component and realize you need to add some state to
it, previously you had to convert it to a class component. Now you can use a Hook
inside the existing function component to manage the state and no need to convert it
into the Class component. Hooks are a new addition to React 16.8. They let you use
state and other React features without writing a class. Instead of Classes, one can use
Hooks in the Functional component as this is a much easier way of managing the
state. Hooks can only be used in functional components, not in-class components.
Functional Components vs Class Components:
Functional Components Class Components

A functional component is just a plain A class component requires you to


JavaScript pure function that accepts extend from React. Component and
props as an argument and returns a React create a render function that returns a
element(JSX). React element.

It must have the render() method


There is no render method used in
returning JSX (which is syntactically
functional components.
similar to HTML)

The class component is instantiated and


Functional components run from top to
different life cycle method is kept alive
bottom and once the function is returned it
and is run and invoked depending on the
can’t be kept alive.
phase of the class component.

Also known as Stateless components as


they simply accept data and display them Also known as Stateful components
in some form, they are mainly responsible because they implement logic and state.
for rendering UI.

React lifecycle methods (for example, React lifecycle methods can be used
componentDidMount) cannot be used in inside class components (for example,
functional components. componentDidMount).

It requires different syntax inside a class


Hooks can be easily used in functional component to implement hooks.
components to make them Stateful. Example:
Example: constructor(props) {
const [name,SetName]= super(props);
React.useState(' ') this.state = {name: ' '}
}

Constructor is used as it needs to store


Constructors are not used.
state.
ReactJS Container and Presentational Pattern in
Components



In this article we will categorise the react components in two types depending on the
pattern in which they are written in application and will learn briefly about these two
categories. We will also discuss about alternatives to this pattern.
Presentational and Container Components
The type of components is decided by components pattern. If the component decides
how the data will be presented on the screen it is called as presentational
component. If the component focuses on what data is to be shown to the user then it
is called as container component
We will discuss individually about these components in this article.
Presentational components:
 Mainly concerned with how things look.
 Have no major dependencies on the rest of the app.
 No connection with the specification of the data that is outside the
component.
 Mainly receives data and callbacks exclusively via props.
 May contain both presentational and container components inside it
considering the fact that it contains DOM markup and styles of their own.
Example: For example, the below code denotes a presentational component, and it
gets its data from the props and just focuses on showing an element.
javascript

// presentational component

const Users = props =>

(<ul>

{props.users.map(user =>

(<li>{itr}</li>))

</ul>)

Container components:
 Mainly concerned with how things work.
 May contain both presentational and container components but does not
have DOM and markup of their own.
 Provide the data and behavior to presentational or other container
components.
 Call flux actions and provides these as callbacks to the presentational
component.
javascript

// container component

classUsersContainerextendsReact.Component{

constructor()

this.state = {

itr: []

componentDidMount() {

axios.get('/users').then(itr => this.setState({ users: itr }))

render() {

return <Usersusers = {this.state.itr

} />

}}

Benefits of Container/Presentational Pattern


 Creates pure functions
 Separates render and fetching logic
 Makes the components more reusable
 Testing the components is easier
Disadvantages of Container/Presentational Pattern
 It’s alternatives perform better
 Usage is decreased as we no longer need class components to create states.
Alternative to Presentational/Container Pattern
This pattern based approach can be easily replaced with using hooks in React. Instead,
of creating different components based on the pattern we can create a single
component which uses hooks to implement different functionality. Since the
introduction of hooks in React the use of this pattern is reduced but it is still used in
some cases as performing tests is easier in this pattern approach.

You might also like