skip to Main Content

I’m relatively new to React and trying to learn by doing some exercises creating components & calling them. In this code segment, I created a functional component useIsFirstRender() which will tell me if it is the first render. However, when I reference this component in the root export function App(), nothing renders. I am expecting it to return true or false, but right now only the text shows up. What logic am I missing here? Thanks!

import React, { useRef } from 'react';

export function useIsFirstRender(): boolean {
  // your code here
  const firstRender = useRef<boolean>(true);

  if (firstRender.current == true) {
    firstRender.current = false;

    return true;
  } else {
    
    return false;
  }
}

export function App() {
  const isFirstRender = useIsFirstRender();
  
  return(
    <div>
    <p>This is or is not the first render: {() => isFirstRender} </p>
    </div>
  )
}

2

Answers


    • The correct term for useIsFirstRender function is custom hook.
    • Boolean values don’t get rendered.

    Fix

    <div>
      <p>This is or is not the first render: {isFirstRender ? "is" : "is not"} </p>
    </div>
    
    Login or Signup to reply.
  1. Lets break it down!

    Your function is not a react component it is a custom hook.
    The main difference between functional components and hooks are that a functional component returns JSX and a custom hook returns business logic.

    First of all react does not render boolean values in JSX so you have to do a conditional rendering to show the difference between the two states of isFirstRender.

    export function App() {
      const isFirstRender = useIsFirstRender();
      
      return(
        <div>
          <p>This is or is not the first render: { isFirstRender ? 'is' : 'is not' } </p>
        </div>
      )
    }
    

    Second one you have to change the useRef hook with a useState hook in your custom hook useIsFirstRender. The reason for that is, that a value change in a useRef hook does not trigger a re-rendering of the component, which is using your custom hook.

    import React, { useState } from 'react';
    
    export function useIsFirstRender(): boolean {
      // change useRef to useState
      const [isFirstRender, setFirstRender] = useState(true);
    
      if (isFirstRender) {
        setFirstRender(false);
      } 
    
      return isFirstRender;
    }
    

    FYI: With this custom hook implementation, your component will return for the first rendering isFirstRender as true and for all upcoming rendering as false.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search