How to check if React Functional Component First Time Render using Hooks

How to check if React Functional Component First Time Render using Hooks
May 18, 2022

A common issue shown by React developers is a functional component rendered again and again when the state or props changed after the first render. This leads to rendering performance issues and unexpected behavior like sending multiple requests and updating states multiple times.

In this article, learn about how to check if your react functional component is rendered the first time.

import { useEffect, useRef } from 'react';
import './App.css';


function App() {
  const ref = useRef(true);


  useEffect(() => {
    const firstRender = ref.current;

    if (firstRender) {
      ref.current = false;
      console.log('First Render');
    } else {
      console.log('Not a first Render');
    }
  })


  return (
    <div className="App">
      <header className="App-header">
        Check if useEffect is called on first render
      </header>
    </div>
  );
}


export default App;

In the above example, we have used useRef, this hook is used to persist the value when the component is rendered. We can change the value of refs as we did above in the example.

So in the above example, we defined refs and stored the flag of the first rendered, after the first render in the if condition refs flag value is updated for future checks.

Use case of this scenario:

  • To get data on the first rendered
  • To perform a specific action on the first render, like show the message to the customer when the component loaded for the first time

If you want to learn more about useRef React Hook, Click here to check the official react tutorial.



Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Master JavaScript by Solving Daily Challenges

Challenge Yourself Daily: Advance Your JavaScript Skills and Career

View Challenges

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates