Home  Reactjs   Does custom ...

Does Custom hook get called every time the component in which it is used renders?

Custom hook gets called every time the component in which it is used renders. This is because custom hooks are just JavaScript functions, and in React, function components (and the hooks inside them) are called on every render.

Example to Illustrate

Let's consider a simple custom hook and a component using it:

import React, { useState, useEffect } from 'react';

function useCustomHook(initialValue) {
  const [value, setValue] = useState(initialValue);

  useEffect(() => {
    console.log('useEffect inside useCustomHook');
  }, [value]);

  return [value, setValue];
}

function App() {
  const [value, setValue] = useCustomHook(0);

  return (
    <div>
      <p>Value: {value}</p>
      <button onClick={() => setValue(value + 1)}>Increment</button>
    </div>
  );
}

export default App;

In this example:

  1. The useCustomHook is called inside the App component.
  2. Every time the App component renders, the useCustomHook function is called.
  3. Inside useCustomHook, useState and useEffect are called as part of the render process.

Breakdown of What Happens on Each Render

  1. Initial Render:

    • App component renders.
    • useCustomHook is called with initialValue of 0.
    • useState initializes value to 0 and returns the state and a setter function.
    • useEffect is called, logging "useEffect inside useCustomHook".
  2. Subsequent Renders:

    • When you click the "Increment" button, setValue updates the state.
    • The state update causes the App component to re-render.
    • During this re-render, useCustomHook is called again.
    • useState returns the current state and the setter function.
    • useEffect is called again if the dependency (value) has changed, logging "useEffect inside useCustomHook".

Key Points

Example with Console Logs

Let's add some console logs to better understand the render process:

import React, { useState, useEffect } from 'react';

function useCustomHook(initialValue) {
  console.log('useCustomHook called');
  const [value, setValue] = useState(initialValue);

  useEffect(() => {
    console.log('useEffect inside useCustomHook');
  }, [value]);

  return [value, setValue];
}

function App() {
  console.log('App component rendering');
  const [value, setValue] = useCustomHook(0);

  return (
    <div>
      <p>Value: {value}</p>
      <button onClick={() => setValue(value + 1)}>Increment</button>
    </div>
  );
}

export default App;

Expected Console Output

  1. Initial Render:

    App component rendering
    useCustomHook called
    useEffect inside useCustomHook
    
  2. After Clicking Increment Button:

    App component rendering
    useCustomHook called
    useEffect inside useCustomHook
    
Published on: Jul 05, 2024, 05:38 AM  
 

Comments

Add your comment