DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 9.

Today's task is to create a hook to tell if it's the first render. The boilerplate code looks like this:


export function useIsFirstRender(): boolean {
  // your code here
}

// if you want to try your code on the right panel
// remember to export App() component like below

// export function App() {
//   return <div>your app</div>
// }

Enter fullscreen mode Exit fullscreen mode

To solve this, first, you create a variable to manage the state which is assigned to a default value. We will be using a ref because refs persists across renders without causing re-renders.

const firstRender = useRef(true) 
Enter fullscreen mode Exit fullscreen mode

The default value is true, because when we run the application for the first time, that is the first render. Subsequent renders will be false.
The function to set the render values:

useEffect(() => {
   firstRender.current = false;
}, [])
  return firstRender.current

Enter fullscreen mode Exit fullscreen mode

To know if we achieved our aim, we would display a message when the application renders.

<div>
{firstRender: "First render" ? "Not first render"}
</div>
Enter fullscreen mode Exit fullscreen mode

We used a tenary operator which basically displays the first message if firstRender is true, or the second message if otherwise.

The final code looks like this:

import React, { useRef, useEffect} from "react";

export function useIsFirstRender(): boolean {
  // your code here
  const firstRender = useRef(true)
  useEffect(() => {
    firstRender.current = false;
  }, [])
  return firstRender.current
}

// if you want to try your code on the right panel
// remember to export App() component like below

export function App() {
  const isFirstRender = useIsFirstRender()

  return (
      <div>
       {isFirstRender ? "First render" : "Not first render"}
      </div>
    )
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)