What is the Virtual DOM?
The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation
of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This
process is called reconciliation.
This approach enables the declarative API of React: You tell React what state you want the UI to
be in, and it makes sure the DOM matches that state. This abstracts out the attribute
manipulation, event handling, and manual DOM updating that you would otherwise have to use
to build your app.
Since “virtual DOM” is more of a pattern than a specific technology, people sometimes say it to
mean different things. In React world, the term “virtual DOM” is usually associated with React
elements since they are the objects representing the user interface. React, however, also uses
internal objects called “fibers” to hold additional information about the component tree. They
may also be considered a part of “virtual DOM” implementation in React.
Is the Shadow DOM the same as the Virtual DOM?
No, they are different. The Shadow DOM is a browser technology designed primarily for scoping
variables and CSS in web components. The virtual DOM is a concept implemented by libraries in
JavaScript on top of browser APIs.
Difference Between a .js and .jsx File in React
Here is a detailed comparison of .js and .jsx files based on various features:
.js File .jsx File
Used for React components with HTML-like
Used for regular JavaScript code.
code (JSX).
Doesn’t include JSX syntax. Includes JSX syntax to define the UI.
Best for writing logic, utility functions, and Best for writing UI components that need
simple components. JSX to render content.
Needs tools like Babel to convert JSX to
Doesn’t need extra tools to run.
JavaScript.
Smaller and simpler if just handling logic. Larger due to JSX code for user interfaces.
Can be used for both JavaScript Focused mainly on creating and rendering
and React logic. UI.
What are .js files in React?
The .js file is a file that contains standard JavaScript code. These files do not contain the UI
related code and are used for writing the logics and the functions.
Used for regular JavaScript code and logic.
Does not include JSX (HTML-like syntax).
Can be used for utility functions, state management, or simple React components.
No extra tools needed to run.
Now, let us understand with the help of the example:
// MyComponent.js
import React from 'react';
const MyComponent = () => {
return React.createElement('h1', null, 'Hello, World!');
};
export default MyComponent;
In this example:
The component is created using React.createElement() instead of JSX.
What is (.jsx) files in React
JSX (JavaScript XML) is an extension of JavaScript that lets developers write HTML-like code
inside JavaScript. Files with the .jsx extension usually contain components written in JSX, which
React then converts into JavaScript function calls.
Used for React components with JSX (HTML-like syntax).
Includes JSX to define the UI structure.
Mainly for creating and rendering the user interface.
Requires tools like Babel to convert JSX into JavaScript.
Now, let us understand with the help of the example:
// MyComponent.jsx
import React from 'react';
const MyComponent = () => {
return <h1>Hello, World!</h1>;
};
export default MyComponent;
In this example
JSX is used to directly write HTML-like code inside the return statement, making the
code more readable and concise.
Key Difference:
.js File: Uses React.createElement() to manually create elements without JSX.
.jsx File: Uses JSX syntax to create elements, which will be compiled
into React.createElement() by tools like Babel.
When to Use a .js and .jsx File in React
Use .js When:
You are writing pure JavaScript code (e.g., functions, utilities).
You are writing React components without JSX.
The file does not contain any JSX expressions, but it might be used in React components
(e.g., configuration files, non-UI logic).
Use .jsx When:
You are writing React components that use JSX syntax.
The file contains JSX code that needs to be transformed into JavaScript by tools
like Babel.
You want to make it clear that the file contains React components written with JSX for
easier readability and better maintenance.
Conclusion
In React, the use of .js and .jsx file extensions helps keep the codebase organized. The .js
extension is typically used for general JavaScript files, such as utility functions and configuration
settings, while .jsx is reserved for React components that contain JSX syntax.
React Components
Last Updated : 04 Apr, 2025
In React, React components are independent, reusable building blocks in a React application
that define what gets displayed on the UI. They accept inputs called props and return React
elements describing the UI.
In this article, we will explore the basics of React components, props, state, and rendering.
What Are React Components?
A component is a building block that encapsulates a piece of the user interface (UI). It defines
the structure and behavior of the UI, either by managing its own state or by receiving data
through props and rendering content accordingly. Components are reusable and can be
composed together to build complex UIs in a modular way.
Components can be reused across different parts of the application to maintain
consistency and reduce code duplication.
Components manage how their output is rendered in the DOM based on their state and
props.
React loads only the necessary components, ensuring optimized performance.
Only the specific Component updates instead of the whole page.
Types of React Components
There are two primary types of React components:
1. Functional Components
Functional components are simpler and preferred for most use cases. They are JavaScript
functions that return React elements. With the introduction of React Hooks, functional
components can also manage state and lifecycle events.
Stateless or Stateful: Can manage state using React Hooks.
Simpler Syntax: Ideal for small and reusable components.
Performance: Generally faster since they don’t require a ‘this’ keyword.
function Greet(props) {
return <h1>Hello, {props.name}!</h1>;
2. Class Components
Class components are ES6 classes that extend React.Component. They include additional
features like state management and lifecycle methods.
State Management: State is managed using the this.state property.
Lifecycle Methods: Includes methods like componentDidMount, componentDidUpdate,
etc.
class Greet extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
Props in React Components
Props (short for properties) are read-only inputs passed from a parent component to a child
component. They enable dynamic data flow and reusability.
Props are immutable.
They enable communication between components.
function Greet(props) {
return <h2>Welcome, {props.username}!</h2>;
// Usage
<Greet username="Anil" />;
State in React Components
The state is a JavaScript object managed within a component, allowing it to maintain and
update its own data over time. Unlike props, state is mutable and controlled entirely by the
component.
State updates trigger re-renders.
Functional components use the useState hook to manage state.
function Counter() {
const [count, setCount] = React.useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count + 1)}>Increment</button>
</div>
);
Rendering a Component
Rendering a component refers to displaying it on the browser. React components can be
rendered using the ReactDOM.render() method or by embedding them inside other
components.
Ensure the component is imported before rendering.
The ReactDOM.render method is generally used in the root file.
ReactDOM.render(<Greeting name="Pooja" />, document.getElementById('root'));
Components in Components
In React, you can nest components inside other components to build a modular and hierarchical
structure.
Components can be reused multiple times within the same or different components.
Props can be passed to nested components for dynamic content.
function Header() {
return <h1>Welcome to My Site</h1>;
function Footer() {
return <p>© 2024 My Company</p>;
function App() {
return (
<div>
<Header />
<p>This is the main content.</p>
<Footer />
</div>
);
export default App;
Best Practices for React Components
Keep Components Small: Each component should do one thing well.
Use Functional Components: Unless lifecycle methods or error boundaries are required.
Prop Validation: Use PropTypes to enforce correct prop types.
State Management: Lift state to the nearest common ancestor when multiple
components need access.
How to use Container Component in ReactJS?
Last Updated : 06 Mar, 2023
The container centers your content horizontally. It’s the most basic layout element. Material UI
for React has this component available for us and it is very easy to integrate. We can use the
Container component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following
command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the
following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default
component where we have written our code.
Javascript
import React from 'react'
import Typography from '@material-ui/core/Typography';
import Container from '@material-ui/core/Container';
const App = () => {
return (
<Container maxWidth="sm">
<Typography component="div" style={{
backgroundColor: 'Orange', height: '100vh'
}}>
Greetings from GeeksforGeeks
</Typography>
</Container>
);
export default App
Step to Run Application: Run the application using the following command from the root
directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following
output:
A child component in React is a component that is nested inside another component, referred
to as the parent component. This parent-child relationship forms a hierarchy that is
fundamental to structuring and organizing React applications. Child components are reusable
pieces of code that encapsulate specific functionalities or UI elements, and they receive data
and functions from their parent components through props.
Code
function ParentComponent() {
const message = "Hello from parent!";
return (
<div>
<h1>Parent Component</h1>
<ChildComponent text={message} />
</div>
);
}
function ChildComponent(props) {
return (
<div>
<p>Message from parent: {props.text}</p>
</div>
);
}
In this example, ChildComponent is a child of ParentComponent. The ParentComponent passes
the message variable as a prop named text to the ChildComponent. The ChildComponent then
renders this prop, displaying the message "Hello from parent!". This demonstrates how data
flows downwards from parent to child components in React.
Namespace components in React refer to a pattern where related components are grouped
under a parent component, acting as a namespace. This approach helps organize code, prevent
naming conflicts, and establish clear relationships between components.
A component namespace is created by adding properties to a parent component, where each
property is assigned a related component. This can be achieved using either function or class
components.
Code
const ParentComponent = ({ children }) => <div>{children}</div>;
const ChildComponentA = () => <div>Child A</div>;
const ChildComponentB = () => <div>Child B</div>;
ParentComponent.ChildA = ChildComponentA;
ParentComponent.ChildB = ChildComponentB;
const App = () => (
<ParentComponent>
<ParentComponent.ChildA />
<ParentComponent.ChildB />
</ParentComponent>
);
JavaScript in JSX with Curly Braces
JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content
in the same place. Sometimes you will want to add a little JavaScript logic or reference a
dynamic property inside that markup. In this situation, you can use curly braces in your JSX to
open a window to JavaScript.
You will learn
How to pass strings with quotes
How to reference a JavaScript variable inside JSX with curly braces
How to call a JavaScript function inside JSX with curly braces
How to use a JavaScript object inside JSX with curly braces
Passing strings with quotes
When you want to pass a string attribute to JSX, you put it in single or double quotes:
App.js
DownloadReset
Fork
10
export default function Avatar() {
return (
<img
className="avatar"
src="https://i.imgur.com/7vQD0fPs.jpg"
alt="Gregorio Y. Zara"
/>
);
Here, "https://i.imgur.com/7vQD0fPs.jpg" and "Gregorio Y. Zara" are being passed as strings.
But what if you want to dynamically specify the src or alt text? You could use a value from
JavaScript by replacing " and " with { and }:
App.js
DownloadReset
Fork
10
11
12
export default function Avatar() {
const avatar = 'https://i.imgur.com/7vQD0fPs.jpg';
const description = 'Gregorio Y. Zara';
return (
<img
className="avatar"
src={avatar}
alt={description}
/>
);
Notice the difference between className="avatar", which specifies an "avatar" CSS class name
that makes the image round, and src={avatar} that reads the value of the JavaScript variable
called avatar. That’s because curly braces let you work with JavaScript right there in your
markup!
Using curly braces: A window into the JavaScript world
JSX is a special way of writing JavaScript. That means it’s possible to use JavaScript inside it—
with curly braces { }. The example below first declares a name for the scientist, name, then
embeds it with curly braces inside the <h1>:
App.js
DownloadResetFork
6
7
export default function TodoList() {
const name = 'Gregorio Y. Zara';
return (
<h1>{name}'s To Do List</h1>
);
Try changing the name’s value from 'Gregorio Y. Zara' to 'Hedy Lamarr'. See how the list title
changes?
Any JavaScript expression will work between curly braces, including function calls like
formatDate():
App.js
DownloadReset
Fork
10
11
12
13
14
15
const today = new Date();
function formatDate(date) {
return new Intl.DateTimeFormat(
'en-US',
{ weekday: 'long' }
).format(date);
export default function TodoList() {
return (
<h1>To Do List for {formatDate(today)}</h1>
);
Where to use curly braces
You can only use curly braces in two ways inside JSX:
1. As text directly inside a JSX tag: <h1>{name}'s To Do List</h1> works,
but <{tag}>Gregorio Y. Zara's To Do List</{tag}> will not.
2. As attributes immediately following the = sign: src={avatar} will read the avatar variable,
but src="{avatar}" will pass the string "{avatar}".
Using “double curlies”: CSS and other objects in JSX
In addition to strings, numbers, and other JavaScript expressions, you can even pass objects in
JSX. Objects are also denoted with curly braces, like { name: "Hedy Lamarr", inventions: 5 }.
Therefore, to pass a JS object in JSX, you must wrap the object in another pair of curly braces:
person={{ name: "Hedy Lamarr", inventions: 5 }}.
You may see this with inline CSS styles in JSX. React does not require you to use inline styles (CSS
classes work great for most cases). But when you need an inline style, you pass an object to the
style attribute:
App.js
DownloadReset
Fork
10
11
12
13
export default function TodoList() {
return (
<ul style={{
backgroundColor: 'black',
color: 'pink'
}}>
<li>Improve the videophone</li>
<li>Prepare aeronautics lectures</li>
<li>Work on the alcohol-fuelled engine</li>
</ul>
);
Try changing the values of backgroundColor and color.
You can really see the JavaScript object inside the curly braces when you write it like this:
<ul style={
backgroundColor: 'black',
color: 'pink'
}>
The next time you see {{ and }} in JSX, know that it’s nothing more than an object inside the JSX
curlies!
Node setup refers to the process of installing Node.js, a runtime environment for executing
JavaScript code outside of a web browser, and its associated package manager, npm. This allows
developers to build server-side applications, command-line tools, and more, using JavaScript.
Here's a breakdown of what's involved:
1. 1. Downloading and Installing Node.js:
Node.js is a free, open-source runtime environment.
You can download the installer from the official website.
Follow the installer's instructions to install Node.js on your machine.
Make sure you add Node.js to your system's PATH environment variable so you
can access it from the command line.
2. 2. npm (Node Package Manager):
npm is the standard package manager for Node.js.
It's included in the Node.js distribution, so you don't need to install it separately.
npm allows you to install, manage, and update Node.js packages (also known as
modules) for your projects.
You can use npm commands to install, update, and uninstall packages.
To use npm in React, you generally use it to install dependencies and manage your project's
packages. This often involves using the command npm install to install packages and then
running commands like npm start to run the development server or npm run build to build the
application.
Creating a package.json file
You can add a package.json file to your package to make it easy for others to manage and install.
Packages published to the registry must contain a package.json file.
A package.json file:
lists the packages your project depends on
specifies versions of a package that your project can use using semantic versioning rules
makes your build reproducible, and therefore easier to share with other developers
Note: To make your package easier to find on the npm website, we recommend including a
custom description in your package.json file.
package.json fields
Required name and version fields
A package.json file must contain "name" and "version" fields.
The "name" field contains your package's name and must be lowercase without any spaces. May
contain hyphens, dots, and underscores.
The "version" field must be in the form x.x.x and follow the semantic versioning guidelines.
Author field
If you want inclusive package author information, in the "author" field use the following format
(email and website are both optional):
Your Name <email@example.com> (https://example.com)
Example
"name": "my-awesome-package",
"version": "1.0.0",
"author": "Your Name <email@example.com> (https://example.com)"
Creating a new package.json file
You can create a package.json file by running a CLI questionnaire or creating a
default package.json file.
Running a CLI questionnaire
To create a package.json file with values that you supply, use the npm init command.
1. On the command line, navigate to the root directory of your package.
cd /path/to/package
2. Run the following command:
npm init
3. Answer the questions in the command line questionnaire.
Your First Component
Components are one of the core concepts of React. They are the foundation upon which you
build user interfaces (UI), which makes them the perfect place to start your React journey!
You will learn
What a component is
What role components play in a React application
How to write your first React component
Components: UI building blocks
On the Web, HTML lets us create rich structured documents with its built-in set of tags like <h1>
and <li>:
<article>
<h1>My First Component</h1>
<ol>
<li>Components: UI Building Blocks</li>
<li>Defining a Component</li>
<li>Using a Component</li>
</ol>
</article>
This markup represents this article <article>, its heading <h1>, and an (abbreviated) table of
contents as an ordered list <ol>. Markup like this, combined with CSS for style, and JavaScript
for interactivity, lies behind every sidebar, avatar, modal, dropdown—every piece of UI you see
on the Web.
React lets you combine your markup, CSS, and JavaScript into custom “components”, reusable
UI elements for your app. The table of contents code you saw above could be turned into a
<TableOfContents /> component you could render on every page. Under the hood, it still uses
the same HTML tags like <article>, <h1>, etc.
Just like with HTML tags, you can compose, order and nest components to design whole pages.
For example, the documentation page you’re reading is made out of React components:
<PageLayout>
<NavigationHeader>
<SearchBar />
<Link to="/docs">Docs</Link>
</NavigationHeader>
<Sidebar />
<PageContent>
<TableOfContents />
<DocumentationText />
</PageContent>
</PageLayout>
As your project grows, you will notice that many of your designs can be composed by reusing
components you already wrote, speeding up your development. Our table of contents above
could be added to any screen with <TableOfContents />! You can even jumpstart your project
with the thousands of components shared by the React open source community like Chakra UI
and Material UI.
Defining a component
Traditionally when creating web pages, web developers marked up their content and then
added interaction by sprinkling on some JavaScript. This worked great when interaction was a
nice-to-have on the web. Now it is expected for many sites and all apps. React puts interactivity
first while still using the same technology: a React component is a JavaScript function that you
can sprinkle with markup. Here’s what that looks like (you can edit the example below):
App.js
DownloadReset
Fork
5
6
export default function Profile() {
return (
<img
src="https://i.imgur.com/MK3eW3Am.jpg"
alt="Katherine Johnson"
/>
And here’s how to build a component:
Step 1: Export the component
The export default prefix is a standard JavaScript syntax (not specific to React). It lets you mark
the main function in a file so that you can later import it from other files. (More on importing in
Importing and Exporting Components!)
Step 2: Define the function
With function Profile() { } you define a JavaScript function with the name Profile.
Pitfall
React components are regular JavaScript functions, but their names must start with a capital
letter or they won’t work!
Step 3: Add markup
The component returns an <img /> tag with src and alt attributes. <img /> is written like HTML,
but it is actually JavaScript under the hood! This syntax is called JSX, and it lets you embed
markup inside JavaScript.
Return statements can be written all on one line, as in this component:
return <img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />;
But if your markup isn’t all on the same line as the return keyword, you must wrap it in a pair of
parentheses:
return (
<div>
<img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
</div>
);
Pitfall
Without parentheses, any code on the lines after return will be ignored!
Using a component
Now that you’ve defined your Profile component, you can nest it inside other components. For
example, you can export a Gallery component that uses multiple Profile components:
App.js
DownloadReset
Fork
10
11
12
13
14
15
16
17
18
19
20
function Profile() {
return (
<img
src="https://i.imgur.com/MK3eW3As.jpg"
alt="Katherine Johnson"
/>
);
export default function Gallery() {
return (
<section>
<h1>Amazing scientists</h1>
<Profile />
<Profile />
<Profile />
</section>
);
Show more
What the browser sees
Notice the difference in casing:
<section> is lowercase, so React knows we refer to an HTML tag.
<Profile /> starts with a capital P, so React knows that we want to use our component
called Profile.
And Profile contains even more HTML: <img />. In the end, this is what the browser sees:
<section>
<h1>Amazing scientists</h1>
<img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
<img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
<img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
</section>
Nested Component
Nesting of Components creates the parent-child relationship between the nested
components. In this approach, children components are nested by including them in the JSX
markup of parent component. It helps in organizing the components in proper structure.
Example: Illustration to showcase the use of nested component.
JavaScriptJavaScriptJavaScript
// Parent.js
import React from 'react'
import Child from './Child'
const Parent = () => {
return (
<div>
<b>This is Parent</b>
<Child />
</div>
export default Parent
Output:
Rendering is React's process of describing a user interface based on the application's current
state and props. The initial render in a React app is the first render when the application starts
up, while re-rendering occurs when there is a change in the state to figure out which parts of
the UI need an update.
What Is React Props?
React is a component-based library that divides the UI into little reusable pieces. In some
cases, those components need to communicate or send data to each other, and the way to
pass data between components is by using props.
As I shared, props is a keyword in React that passes data from one component to another. But
the important part here is that data with props are being passed in a unidirectional flow. This
means it’s passed one way from parent to child.
Props data is read-only, which means that data coming from the parent shouldn’t be changed
by child components.
How to Use Props in React With Example
I will be explaining how to use props step-by-step. There are three steps to using React props:
1. Define an attribute and its value (data).
2. Pass it to the child component(s) by using props.
3. Render the props data.
In this example, we have a ParentComponent including another ChildComponent:
class ParentComponent extends Component {
render() {
return (
<h1>
I'm the parent component.
<ChildComponent />
</h1>
);
And this is our ChildComponent:
const ChildComponent = () => {
return <p>I'm the 1st child!</p>;
};
The problem here is that when we call the ChildComponent multiple times, it renders the
same string again and again:
class ParentComponent extends Component {
render() {
return (
<h1>
I'm the parent component.
<ChildComponent />
<ChildComponent />
<ChildComponent />
</h1>
);