An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
May 27, 2021 07:44 am GMT
Original Link: https://dev.to/aasthapandey/prevent-unnecessary-renders-react-memo-389b
Prevent unnecessary renders (React.memo)
React.memo is helpful in, preventing unnecessary renders,
in the below snippet, I'm using React.memo this component will only be rendered when the component gets mounted and if the props quantity changes otherwise it'll keep displaying the previously rendered component.
But if the Cart component itself has some state or using useState, useContext, useReducer it will surely be rendered.
//Cart.jsconst Cart = ({ quantity }) => { console.log("Rendered Cart!"); return <>Number of item is {quantity}</>;};export default React.memo(Cart);
In the below snippet, the Cart component is being rendered and we are passing in quantity as props, so whenever one clicks on the quantity button, the Cart component will be re-rendered but won't get re-rendered when you type in something in the search text box.
//App.jsimport Cart from "./Cart";import { useState } from "react";export default function App() { const [quantity, setQuantity] = useState(0); const [search, setSearch] = useState(); return ( <div className="App"> <Cart quantity={quantity} /> <hr /> <label>Quantity </label> <button onClick={() => { setQuantity(quantity + 1); }} > {quantity} </button> <hr /> <label>Search </label> <input onChange={(event) => { setSearch(event.target.value); }} ></input> </div> );}
Original Link: https://dev.to/aasthapandey/prevent-unnecessary-renders-react-memo-389b
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To