React Components
React Components
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';
Javascript
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
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
Javascript
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
// 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"));
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 />;
ReactDOM.render(
<Welcome />,
document.getElementById("root")
);
Output:
// Navbar Component
const Navbar=()=>
{
return <h1>This is Navbar.< /h1>
}
// Sidebar Component
const Sidebar=()=> {
return <h1>This is Sidebar.</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.
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
// 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
render(){
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
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
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
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
return (
<div>
Click Here!
</button>
</div>
);
ReactDOM.render(
<React.StrictMode>
<Example />
</React.StrictMode>,
document.getElementById('root')
);
useEffect(() => {
console.log("Mounting...");
});
return (
<h1>
Geeks....!
</h1>
);
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
ReactDOM.render(
<React.StrictMode>
<Example />
</React.StrictMode>,
document.getElementById('root')
);
return (
<h1>{props.data}</h1>
);
function propsExample() {
return (
<div>
Click Here!
</button>
{change ?
</div>
);
Output: You will see the output like this in your browser.
constructor(props) {
super(props);
}
componentDidMount() {
console.log("componentDidMount()");
changeState() {
render() {
return (
<div>
<h1>GeeksForGeeks.org, Hello{this.state.hello}</h1>
<h2>
</h2>
</div>);
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate()");
return true;
componentDidUpdate() {
console.log("componentDidUpdate()");
<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
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";
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>
)
}
}
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
React lifecycle methods (for example, React lifecycle methods can be used
componentDidMount) cannot be used in inside class components (for example,
functional components. componentDidMount).
// presentational component
(<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() {
render() {
} />
}}