React Js Express Js Unit-4
React Js Express Js Unit-4
1
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
Unit :4
Memo, Refs,Props andContext
Memo
Introduction to Refs: Refs, Refs with Class
Components, Forwarding Refs and Portals
Components: Higher Order Components
Props Again!: Rendering Props and Context
HTTP: HTTP and React, GET and React, POST and React.
Memo
In React, the memo function is a higher-order component (HOC) that you
can use to memoize functional components. Memoization is a technique to
optimize rendering performance by preventing unnecessary re-renders of
components. When a component is wrapped with memo, React will only re-
render the component if its props have changed.
// Usage
const ParentComponent = () => {
const [prop1, setProp1] = React.useState('Value 1');
const [prop2, setProp2] = React.useState('Value 2');
return (
<div>
<MemoizedComponent prop1={prop1} prop2={prop2} />
<button onClick={() => setProp1('New Value 1')}>Change Prop
1</button>
<button onClick={() => setProp2('New Value 2')}>Change Prop
2</button>
</div>
);
};
3
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
Javascript
import React, { memo } from 'react';
// Usage
const ParentComponent = () => {
const [prop1, setProp1] = React.useState('Value 1');
const [prop2, setProp2] = React.useState('Value 2');
return (
<div>
<MemoizedComponent prop1={prop1} prop2={prop2} />
<button onClick={() => setProp1('New Value 1')}>Change Prop
1</button>
<button onClick={() => setProp2('New Value 2')}>Change Prop
2</button>
</div>
);
};
4
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
In this example:
5
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
Introduction to Refs: Refs, Refs with Class
Components, Forwarding Refs and Portals
Refs in React are a feature that allows you to access and interact with DOM elements or
React components directly. They provide a way to reference a specific element or
component imperatively rather than declaratively. Refs are commonly used for managing
focus, triggering imperative animations, integrating with third-party DOM libraries, and
accessing DOM measurements.
Javascript Example
import React, { Component } from 'react';
render() {
return <div ref={this.myRef}>Hello World</div>;
}
}
6
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
Javascript Example
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = null;
}
render() {
return <div ref={this.setRef}>Hello World</div>;
}
}
3. Forwarding Refs:
Forwarding refs allows components to pass refs through to their children. This is useful
when you're building a reusable component that needs to access the underlying DOM node
or component instance.
Javascript Example
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
Portals:
Portals provide a way to render children into a DOM node that exists outside the DOM
hierarchy of the parent component. This is useful for scenarios like modals, tooltips, and
popovers, where you want to render content outside the normal DOM flow.
7
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
Javascript Example
import React from 'react';
import ReactDOM from 'react-dom';
componentDidMount() {
modalRoot.appendChild(this.el);
}
componentWillUnmount() {
modalRoot.removeChild(this.el);
}
render() {
return ReactDOM.createPortal(this.props.children, this.el);
}
}
// Usage
<Modal>
<div>Modal Content</div>
</Modal>;
These are some of the key aspects of using refs in React, including working with DOM
elements, class components, forwarding refs, and portals. Refs are a powerful tool in React,
but they should be used sparingly and judiciously, as direct DOM manipulation can bypass
React's declarative programming model and lead to harder-to-maintain code.
8
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
Example
import React from 'react';
render() {
// Render the original component with any props passed to it
return <WrappedComponent {...this.props} />;
}
}
return WithLogger;
};
9
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
// Enhance MyComponent with withLogger HOC
const MyComponentWithLogger = withLogger(MyComponent);
// Usage
ReactDOM.render(<MyComponentWithLogger/>, document.getElementById('root'));
In this example:
10
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
Props Again!: Rendering Props and
Context
Rendering Props and Context are two powerful techniques in React.js for passing data from a
parent component to its descendants. Let's discuss each one:
Rendering Props:
Rendering Props is a pattern where a component accepts a function as a prop, which it then calls
to render content. This pattern allows for greater flexibility and reusability, as it enables
components to render content based on the logic provided by the parent component.
// Parent component
class ParentComponent extends React.Component {
render() {
return (
<div>
{/* Passing a function as a prop */}
<ChildComponent render={(name) => <div>Hello, {name}!</div>} />
</div>
);
}
}
// Child component
class ChildComponent extends React.Component {
render() {
// Calling the function passed as a prop
return <div>{this.props.render("World")}</div>;
}
}
11
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
// Usage
ReactDOM.render(<ParentComponent />, document.getElementById('root'));
Context:
Context provides a way to pass data through the component tree without having to pass props
down manually at every level. It's particularly useful for passing data that is needed by many
components at different levels of the component tree.
// Create a context
const MyContext = React.createContext();
render() {
return <div>Hello, {this.context}!</div>;
}
}
12
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
// Usage
ReactDOM.render(<ParentComponent />, document.getElementById('root'));
Rendering Props and Context are both powerful techniques for passing data in React.js
applications, and the choice between them depends on the specific use case and requirements
of your application.
13
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
HTTP: HTTP and React, GET and
React, POST and React.
In React.js, you can perform HTTP requests, such as GET and POST, using various
methods and libraries. Two popular libraries for making HTTP requests in React are
Axios and the built-in Fetch API. Let's explore how you can use these libraries to
perform GET and POST requests in a React application.
function App() {
const [data, setData] = useState(null);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => {
setData(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);
return (
<div>
{data ? (
<div>Data: {JSON.stringify(data)}</div>
):(
14
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
<div>Loading...</div>
)}
</div>
);
}
In React.js, you can perform HTTP requests, such as GET and POST, using various
methods and libraries. Two popular libraries for making HTTP requests in React are
Axios and the built-in Fetch API. Let's explore how you can use these libraries to
perform GET and POST requests in a React application.
javascript
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => {
setData(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);
15
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
return (
<div>
{data ? (
<div>Data: {JSON.stringify(data)}</div>
):(
<div>Loading...</div>
)}
</div>
);
}
Here's an example of making a POST request with the Fetch API in a React component:
import React, { useState } from 'react';
function App() {
const [responseData, setResponseData] = useState(null);
return (
16
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
<div>
<button onClick={postData}>Send POST Request</button>
{responseData && (
<div>Response: {JSON.stringify(responseData)}</div>
)}
</div>
);
}
In React.js, you can perform HTTP requests, such as GET and POST, using various
methods and libraries. Two popular libraries for making HTTP requests in React are
Axios and the built-in Fetch API. Let's explore how you can use these libraries to
perform GET and POST requests in a React application.
bash
npm install axios
Then, you can make a GET request in a React component like this:
javascript
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => {
setData(response.data);
17
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);
return (
<div>
{data ? (
<div>Data: {JSON.stringify(data)}</div>
):(
<div>Loading...</div>
)}
</div>
);
}
Here's an example of making a POST request with the Fetch API in a React component:
javascript
import React, { useState } from 'react';
function App() {
const [responseData, setResponseData] = useState(null);
return (
<div>
<button onClick={postData}>Send POST Request</button>
{responseData && (
<div>Response: {JSON.stringify(responseData)}</div>
)}
</div>
);
}
In these examples, axios.get and fetch are used to make GET and
POSTrequests,respectively. Upon successful responses, the retrieved data is stored in
React state (data or responseData) and then displayed in the component. Additionally,
error handling is implemented to handle any network or API errors that may occur
during the request.
19