react hooks usememo code example
Example 1: usememo hook react
const [a,setA]=useState(0);
const [b,setB]=useState(0);
const pow=(a)=>{
return Math.pow(a,2);
}
var val= useMemo(()=>{
return pow(a); // calling pow function using useMemo hook
},[a]); // only will be called once a will changed (for "a" we can maintain state)
return(
<input type="text" onChange={(e)=>{setA(e.target.value)}}>
<input type="text" onChange={(e)=>{setB(e.target.value)}}>
{val} // to access the value from useMemo
)
Example 2: use callback vs use memo
// They both take a function and an array of dependencies:
useCallback(() => {···}, [dependency1, dependency2]);
useMemo(() => {···}, [dependency1, dependency2]);
// So what is the difference?
// useCallback returns its function uncalled so you can call it later
// therefore, it gives you back the function's reference
// useMemo calls its function and returns the result.
// therefore, it gives you back the function's return value