Skip to content

Hooks that is necessary to know while working with ReactJS

Notifications You must be signed in to change notification settings

NishChal370/ReactJS-Hooks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

useMemo Hooks

It is used to optimize performance and only call the function when needed. It basically cache the result of invoked function.

function App() {
      const [valueFirst, setValueFirst] = useState(0);
      const [valueSecond, setValueSecond] = useState(0);

      const increaseValueFirstHandler = ()=>{
            setValueFirst(valueFirst+1);
      }

      const increaseValueSecondHandler = ()=>{
            setValueSecond(valueSecond+1);
      }

      /**
       * Here memo is used so that this function will not be called when
       * valueSecond changed.
       */
      const isEvenNumber = useMemo( ()=>{
            console.log("Calculate even number of first ");

            return valueFirst %2 === 0 ? 'Even' : 'Odd';
      },[valueFirst] );

      return (
            <div className="App">
                  <button onClick={increaseValueFirstHandler}>Click First value = {valueFirst}</button>
                  <p>First Value is {isEvenNumber}</p>
                  
                  <button onClick={increaseValueSecondHandler}>Click Second value = {valueSecond}</button>
            </div>
      );
}