What is the use of shouldComponenUpdate() methods in ReactJS ?
The `shouldComponentUpdate()` method in class-based components is invoked before each re-render, excluding the initial render, triggered by updated props or state. Its default value is true but can be customized using conditional JSX, mainly employed for optimizing React web apps by preventing unnecessary component re-renders.
Prerequisite:
Steps to Create the React Application:
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: Run the development server by using the following command:
npm start
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Approach:
- App.js Component:
- Contains a `geeksCourses` array with course data and a `cart` state using the `useState()` hook.
- Applies basic styles and passes down props with respective names.
- Courses.js Component:
- Adds basic styles, destructures `geekCourses` and `setCart` properties from props.
- Implements an onClick handler for each course in the array to update the user’s cart.
- Cart.js Component:
- Demonstrates the use of the `shouldComponentUpdate()` method.
- Compares `nextProps` (title) with the current cart’s title to determine if the component should update.
- Uses conditional logic to display data when the cart is initially empty and shows the cart otherwise.
Example: Write the following code in the App.js, Courses.js and Cart.js.
import { useState } from "react";
import "./App.css";
import Cart from "./Components/Cart";
import Courses from "./Components/Courses";
function App() {
let geekCourses = [
{
title: "App development with Java and Kotlin",
price: 10000,
duration: 5,
mentor: "Aman Negi",
TA: "Rahul Negi",
classesPerWeek: 5,
},
{
title: "Web development Nodejs",
price: 9000,
duration: 4,
mentor: "Riya Rawat",
TA: "Mihir Rawat",
classesPerWeek: 4,
},
{
title: "MERN stack ",
price: 12000,
duration: 6,
mentor: "Kartik Sayana",
TA: "Amogh Sayana",
classesPerWeek: 6,
},
{
title: "Machine Learning with python",
price: 10000,
duration: 6,
mentor: "Rohit Jain",
TA: "Utkarsh Jain",
classesPerWeek: "5",
},
];
const [cart, setCart] = useState({});
return (
<>
<div style={{ width: "50%",
margin: "auto",
textAlign: "center"
}}>
<h2>Geeks Courses</h2>
</div>
<div style={{ display: "flex", alignItems: "center" }}>
<Courses geekCourses={geekCourses}
setCart={setCart} cart={cart} />
<Cart cart={cart} />
</div>
</>
);
}
export default App;
//Courses.js
import React from "react";
import PropTypes from "prop-types";
const Courses = ({ geekCourses, setCart }) => {
let displayCourses = geekCourses.map((course, idx) => {
return (
<div
key={idx}
style={{
border: "2px solid rgb(91, 222, 115)",
margin: "5px",
width: "20vw",
borderRadius: "10px",
boxShadow: "5px 3px 11px -1px rgba(0,0,0,0.46)",
padding: "5px",
}}
>
<h3> {course.title} </h3>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<span style={{ margin: "5px" }}>
<strong>Duration:</strong> {course.duration} days
</span>
<span style={{ margin: "5px" }}>
<strong>Price:</strong> {course.price} Rs
</span>
</div>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
margin: "10px 5px",
}}
>
<span style={{ margin: "5px" }}>
<strong>Mentor:</strong> {course.mentor}
</span>
<span style={{ margin: "5px" }}>
<strong>TA:</strong> {course.TA}
</span>
</div>
<div
style={{
display: "flex",
justifyContent: "space-around",
alignItems: "center",
}}
>
<button
style={{
padding: "2px 15px",
borderRadius: "10px",
border: "none",
backgroundColor: "rgb(3, 252, 86)",
fontWeight: "bold",
cursor: "pointer",
}}
onClick={() => {
let newCart = {
title: course.title,
mentor: course.mentor,
price: course.price,
};
setCart(newCart);
}}
>
BUY
</button>
</div>
</div>
);
});
return (
<>
<div style={{ width: "60vw" }}>
<div
style={{
display: "flex",
flexWrap: "wrap",
padding: "5px",
justifyContent: "center",
}}
>
{displayCourses}
</div>
</div>
</>
);
};
export default Courses;
//Cart.js
import React, { Component } from "react";
export class Cart extends Component {
shouldComponentUpdate(nextProps, nextState) {
const { cart } = this.props;
console.log("nextProps", nextProps.cart);
if (Object.keys(cart).length === 0) return true;
return nextProps.cart.title !== this.props.cart.title;
}
render() {
console.log("rendering Cart Component");
const { cart } = this.props;
let cartData = (
<>
<div style={{ display: "flex",
justifyContent: "space-between" }}>
<h4>{cart.title}</h4>
<h5> {cart.mentor} </h5>
</div>
<div style={{ display: "flex",
justifyContent: "space-between" }}>
<strong>{cart.price}</strong>
<button
style={{
padding: "2px 15px",
borderRadius: "10px",
border: "none",
backgroundColor: "rgb(3, 252, 86)",
fontWeight: "bold",
cursor: "pointer",
}}
>
CHECKOUT
</button>
</div>
</>
);
return (
<div
style={{
width: "35vw",
height: "150px",
border: "3px solid rgb(3, 252, 82)",
borderRadius: "10px",
padding: "10px",
margin: "5px",
}}
>
{Object.keys(cart).length === 0 ? (
<h3>Your cart is empty</h3>
) : (
<>
<h3 style={{ margin: "2px" }}>
Your-Cart
</h3> {cartData}
</>
)}
</div>
);
}
}
export default Cart;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: