6

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();
}, []);
mongonoob
  • 103
  • 1
  • 5
  • 2
    It's not possible to use [`useCallback` inside `useEffect`](https://reactjs.org/docs/hooks-rules.html#:~:text=Instead%2C%20always%20use%20Hooks%20at,multiple%20useState%20and%20useEffect%20calls.) though. – Ryan Le Sep 07 '21 at 15:22

1 Answers1

6

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

Viet
  • 12,133
  • 2
  • 15
  • 21