Search code examples
reactjsreact-hooksuse-effectusecallback

What is the difference between defining a function outside useEffect and calling that function inside of it and defining a function inside useEffect?


I have few scenarios and I'd like to understand the differences in regards to rendering and performance.

The example shown below is for a simple function but please consider a more complex one too as well as an async function.

Scenario 1: Defining function and calling it inside useEffect.

useEffect(() => {
  function getBooks() {
    console.log('I get books!');
  }
  getBooks();
}, []);

Scenario 2: Defining function outside UseEffect and calling it inside of it.

function getBooks() {
  console.log('I get books!');
}
useEffect(() => {
  getBooks();
}, []);

Scenario 3: Using useCallback to define the function outside of UseEffect and calling it inside of it.

const getBooks = useCallback(() => {
  console.log('I get books!');
}, []);

useEffect(() => {
  getBooks();
}, []);

Scenario 4: Using useCallback to define a function inside UseEffect and calling it also inside UseEffect.

useEffect(() => {
  const getBooks = useCallback(() => {
    console.log('I get books!');
  }, []);
  getBooks();
}, []);

Solution

  • Case 1: getBooks only create once time inside the useEffect. And getBooks only create when useEffect was called.

    Case 2: getBooks create on the component. And when the component re-render, getBooks is also re-create.

    Case 3: It has the same case 2 but it only creates once time. It is like case 1. But we can customize dependencies for each. They will be independent of each other

    Case 4: Wrong case. It's not possible to use useCallback inside useEffect: https://reactjs.org/docs/hooks-rules.html