useCallback Hooks in React



useCallback is React hook. It takes function that executes if the value inside the dependency array changes. useCallback returns a memorised version of the provided callback function. Memorised version the function does not get executed at every component render unless the value in its dependency array changes.


import {useCallback} from "react";

To use useCallback hooks, first import it at the top of the file or use it like React.useCallback


import {useCallback, useEffect} from "react";

export function Mycomponent(){
  const [location, setLocation] = useState('london');
  const [name, setName] = useState('John');
  
  useEffect(() => {
    callAPI();
    
    //some action
    setName('Doe');
  }, [name]);
  
  //first parameter is a callback function
  //second parameter is a dependency array
  // only when the value inside dependancy array changes
  //callAPI function will be called
  const callAPI = useCallback(async () =>{
    //call weather API to get london weather.
  }, [location]);
  
  return(
  

useCallback example

); }
Previous Post Next Post