React Component API: Everything You Need to Know
Introduction
React is also referred to as a JavaScript
library for building a single-page application. It's used in many global
companies for large projects, Such as Google, Amazon, Microsoft, etc.
All React applications are created using
components because they provide a more reusable, independent user interface
that handles its own re-rendering. In this article, we will discuss how to
handle the React component API that every developer should know.
React Component
Components in React work as a function or
class that returns the JSX element. It’s used for managing the lifecycle
methods, state, methods, or props, hooks, and also interacts with the component
tree effectively. Component uses the state and props to send data from parent
to child and within the component.
Types of Components
Components are divided into two types,
which are shown below in detail:
1. Functional component:
This component is just like the JavaScript
functions that return the JavaScript XML. It uses React hooks, allows for
lifecycle methods, and other features without class components.
Syntax:
function
ComponentName(props) {
return (
<div>
{/* Write your JSX Code here */}
</div>
);
}
export default ComponentName;
Example
Code:
import React from
"react";
function MongoInfo() {
return (
<div>
<h3>MongoDB - Points</h3>
<ul>
<li>NoSQL Database</li>
<li>Stores data in JSON-like
documents</li>
<li>High performance &
scalability</li>
</ul>
</div>
);
}
export default MongoInfo;
Output:
MongoDB - Points
- NoSQL Database
- Stores data in JSON-like documents
- High performance & scalability
2. Class Components:
These components allow for lifecycle
methods and other features to be easily. It’s introduced in ES6 features that
extend React.Component includes a render() method that returns
the JSX element.
Syntax:
import React, { Component
} from "react";
class ComponentName
extends Component {
render() {
return (
<div>
{/* write your JSX code here */}
</div>
);
}
}
export default
ComponentName;
Example
Code:
import React, { Component
} from "react";
class ReactInfo extends
Component {
render() {
return (
<div>
<h2>ReactJS - Key
Points</h2>
<ul>
<li>Component-Based
Architecture</li>
<li>Reusable UI
Components</li>
<li>Virtual DOM for fast
rendering</li>
</ul>
</div>
);
}
}
export default ReactInfo;
Output:
ReactJS - Key Points
- Component-Based Architecture
- Reusable UI Components
- Virtual DOM for fast rendering
Common features of Component API
The Component API provides built-in
methods and properties that help developers create, update, and manage
components in a React application. It uses many features, which are as follows:
1) State
State helps send the data within the
component. It is mutable, and changing the state triggers the updating of the
user interface.
Example
Code:
import React, { useState
} from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() =>
setCount(count + 1)}>Increase</button>
<button onClick={() =>
setCount(count - 1)}>Decrease</button>
</div>
);
}
export default Counter;
Output:
2) Props
Props refer to the properties. It allows
for sending the data from parent to child components. This provides a
unidirectional data flow. Props are read-only, which means you cannot modify
the child component.
Example
Code:
import React from
"react";
function TechList(props)
{
return (
<div>
<h2>Top trending
Technologies:</h2>
<ul>
{props.techs.map((tech, index) => (
<li
key={index}>{tech}</li>
))}
</ul>
</div>
);
}
function App() {
const technologies = ["React",
"Node.js", "MongoDB", "Express"];
return <TechList techs={technologies}
/>;
}
export default App;
Output:
Top trending
Technologies:
- React
- Node.js
- MongoDB
- Express
3) Lifecycle Methods
These methods are used only in class
components. It contains three phases:
mounting, updating, and Unmounting.
Mounting: It
is also known as the first phase of this method. It helps to create the
component and add it to the element in the DOM.
This contains several methods that are
shown below:
- · Constructor()
- · getDerivedStateFromProps()
- · render()
- · componentDidMount()
Example
Code:
import React, { Component
} from "react";
class Counter extends
Component {
constructor(props) {
super(props);
this.state = { count: 0 };
console.log("Constructor
called");
}
componentDidMount() {
console.log("Component Mounted"
);
}
render() {
return <h2>Initial Count: {this.state.count}</h2>;
}
}
export default Counter;
Output:
Initial Count: 0
Updating: This
phase is used for updating the state or props. This contains several methods
that are shown below:
- ·
shouldComponentUpdate()
- ·
render()
- ·
getSnapshotBeforeUpdate()
- ·
componentDidUpdate()
Example
Code:
import React, { Component
} from "react";
class Hello extends
Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
shouldComponentUpdate(nextProps, nextState) {
if (nextState.count > 5) {
console.log("Update blocked (count
> 5)");
return false;
}
console.log("Component will
update");
return true;
}
componentDidUpdate(prevProps, prevState) {
console.log(`Count changed from ${prevState.count}
to ${this.state.count}`);
}
render() {
return (
<div>
<h2>Count:
{this.state.count}</h2>
<button onClick={() =>
this.setState({ count: this.state.count + 1 })}>
Increase
</button>
</div>
);
}
}
export default Hello;
Output:
Unmounting: This
phase is used when you are deleting a component from the DOM elements. This
contains only one method, such as componentWillUnmount().
Example
Code:
import React, { Component
} from "react";
class AutoMessage extends
Component {
timer;
componentDidMount() {
this.timer = setTimeout(() => {
console.log("Message displayed for 5
seconds ");
}, 5000);
console.log("Timer started");
}
componentWillUnmount() {
clearTimeout(this.timer);
console.log("Timer cleared (component
unmounted)");
}
render() {
return <h2>This message will
disappear when unmounted!</h2>;
}
}
class App extends
Component {
state = { show: true };
render() {
return (
<div>
{this.state.show &&
<AutoMessage />}
<button onClick={() =>
this.setState({ show: false })}>
Remove Message
</button>
</div>
);
}
}
export default App;
Output:
4) Context API
With the use of the context API, you can
easily manage data sharing or global state from one component to another. This
process is called the props drilling. We use React.createContext() for
creating a context object. It doesn’t require any dependencies or third-party
libraries for managing the Redux state.
Syntax:
import { useContext }
from 'react';
function hello() {
const data = useContext(dataContext);
// Write your JSX code here
Example
Code:
import React, {
createContext, useContext, useState } from "react";
const AuthContext =
createContext();
function App() {
const [user, setUser] = useState(null);
return (
<AuthContext.Provider value={{ user,
setUser }}>
<Navbar />
<LoginPanel />
</AuthContext.Provider>
);
}
function Navbar() {
const { user } = useContext(AuthContext);
return (
<div style={{ background:
"#ddd", padding: "10px" }}>
<h2>My App</h2>
<p>{user ? `Welcome, ${user}` :
"Not logged in"}</p>
</div>
);
}
function LoginPanel() {
const { user, setUser } =
useContext(AuthContext);
const login = () => setUser("Tpoint
Tech");
const logout = () => setUser(null);
return (
<div style={{ marginTop:
"20px" }}>
{user ? (
<button
onClick={logout}>Logout</button>
) :
(
<button
onClick={login}>Login</button>
)}
</div>
);
}
export default App;
Output:
5) Functional components with Hooks:
This component uses React Hooks such as
useState, useEffect, and useContext. It provides a way to manage the state and
lifecycle methods. It is also referred to as the stateless component.
Example
Code:
import React, { useState,
useCallback } from "react";
function Button({
handleClick, children }) {
console.log(`Rendering button -
${children}`);
return <button
onClick={handleClick}>{children}</button>;
}
function Change() {
const [count, setCount] = useState(0);
const [other, setOther] = useState(10);
const increment = useCallback(() => {
setCount((prev) => prev + 1);
}, []);
return (
<div>
<h1>Count: {count}</h1>
<Button
handleClick={increment}>Increment</Button>
<h2>Other State: {other}</h2>
<button onClick={() =>
setOther(other + 1)}>Change Other</button>
</div>
);
}
export default Change;
Output:
Conclusion
This article provides a deeper
understanding of the React Component API
from basic to advance levels. React components are essential components for
managing the data, responding to changes, and interacting with each other. It
provides many features such as props, state, context API, lifecycle methods,
and error boundaries, etc, to build React for both small and large projects.
I recommend that you learn ReactJS from
the Tpoint tech website, as it provides React.js tutorials, interview
questions, and all other informative topics in easy language.

Comments
Post a Comment