react js-tutorial

React useMemo Hook

The usage The hook called Memo in React’s functional component returns a value that has been memoized. Memorization is a broad term used in computer science when we don’t need to recompute a function with a particular parameter the next time because it delivers the cached result. A memoized function keeps track of the outcomes for a specific set of inputs. For instance, if a function exists to add two numbers, and we pass in the parameters 1 and 2 for the first time, the function will add these two numbers and return 3, but if the same inputs are provided again, we will return the cached value, or 3, rather than performing the add function calculation once more.

When the state and props of a React component remain constant and the component does not re-render, we use this idea to ensure that the component displays the same output. Our React application’s performance is enhanced by the useMemo hook.

Syntax

const memoizedValue = useMemo(functionThatReturnsValue, arrayDepencies)

Example: When we don’t use the useMemo Hook.

import React, {useState} from 'react';
  
function App() {
  const [number, setNumber] = useState(0)
  const squaredNum =  squareNum(number);
  const [counter, setCounter] = useState(0);
  
 // Change the state to the input
  const onChangeHandler = (e) => {
    setNumber(e.target.value);
  }
    
  // Increases the counter by 1
  const counterHander = () => {
    setCounter(counter + 1);
  }
  return (
    <div className="App">
      <h1>Welcome to Learn Code Zone</h1>
      <input type="number" placeholder="Enter a number" 
        value={number} onChange={onChangeHandler}>
      </input>
        
      <div>OUTPUT: {squaredNum}</div>
      <button onClick= {counterHander}>Counter ++</button>
      <div>Counter : {counter}</div>
    </div>
  );
}
  
// function to square the value
function squareNum(number){
  console.log("Squaring will be done!");
  return Math.pow(number, 2);
}
  
export default App;

Output

In the sample above, there is an App component that performs two functions. One involves square-rooting the input and increasing the counter. Here, the component redraws itself anytime one of the two states, number and counter, changes. For instance, the function squareNum runs if the input value of the number is changed, and it also runs if the counter is increased once more.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.