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
useIsFirstRender
function is custom hook.Fix
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 acustom 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
.Second one you have to change the
useRef
hook with auseState
hook in your custom hookuseIsFirstRender
. 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.FYI: With this custom hook implementation, your component will return for the first rendering
isFirstRender
as true and for all upcoming rendering as false.