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.