This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for React Coding Question on BFE.dev
9. useEffectOnce()
Solution:
Here is one possible implementation using the useEffect()
hook:
import { useEffect } from 'react';function useEffectOnce(effect) { useEffect(effect, []);}
This implementation takes an effect function as an argument, and calls it with an empty dependency array []
. This means that the effect will only run once, when the component is mounted.
Here's an example of how to use this hook:
import React from 'react';import { useEffectOnce } from './useEffectOnce';function MyComponent() { useEffectOnce(() => { console.log('Mounted!'); }); return ( <div> <h1>Hello, world!</h1> </div> );}
In this example, the useEffectOnce()
hook is used to log a message to the console when the component is mounted. The message will only be logged once, thanks to the useEffectOnce()
hook.