What is useCallback and Why it's required.


The useCallback hook is used where we have to check the reference equality (i.e functions, callback functions)

where we have normal props check we can user React.Memo ( remember React.Memo is nothing to do with useMemo hook )

useCallback is mainly used when we pass function as callback function in react components


Before Using Callback


const incrementSalary = () => {
   setSalary(salary + 1000 )
}


After Using callback funcation

const incrementSalary = useCallback(() => {
   setSalary(salary + 1000 )
}, [age])

Pure Memoization in JavaScript | Closures Example

function square(num) {
  return num * num;
}

function memoizedSquare() {
  let cache = {}
  return function optimizedSquare(num) {
    //console.log(JSON.stringify(cache));
    if(num in cache) {
      console.log('returning from cache);
      return cache[num];
    }else {
      console.log('computing square');
      const result = square(num);
      cache[num] = result;
      return result;
    }
  }
}

const memoSquare = memoizedSquare();
console.log(memoSquare(10));
console.log(memoSquare(20));
console.log(memoSquare(30));
console.log(memoSquare(30));

What is Closures is javascript

Closures 

Function along with its lexical scope bundled together forms a closure. it's called Closures.