BFE.devAI解答 - React 代码题
3. useIsFirstRender()
import { useRef, useEffect } from 'react';function useIsFirstRender() { const isFirstRenderRef = useRef(true); useEffect(() => { isFirstRenderRef.current = false; }, []); return isFirstRenderRef.current;}function App() { const isFirstRender = useIsFirstRender(); // only true for the first render return <div>{isFirstRender ? 'First render' : 'Not first render'}</div>;}
This code creates a custom hook called useIsFirstRender. It uses the useRef hook to keep track of whether it is the first render or not. It initializes the isFirstRenderRef variable to true initially. The useEffect hook is used to update isFirstRenderRef.current to false after the first render.
The App component calls the useIsFirstRender hook, which returns true for the first render and false for subsequent renders. The component uses this value to conditionally render text.