DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 14

The task is to create useEffectOnce() hook, which, as the name implies, runs the effect once.

The boilerplate code is:

import { EffectCallback } from 'react' export function useEffectOnce(effect: EffectCallback) { // your code here } // if you want to try your code on the right panel // remember to export App() component like below // export function App() { // return <div>your app</div> // } 
Enter fullscreen mode Exit fullscreen mode

The solution to this is very straightforward. To ensure that the useEffect runs only once, you pass [] as the dependency array, indicating that it has no dependency.

import React, { useEffect, EffectCallback } from 'react' export function useEffectOnce(effect: EffectCallback) { useEffect(effect, []) } 
Enter fullscreen mode Exit fullscreen mode

The use case for the useEffectOnce hook is to ensure that you don't accidentally add dependencies when you intend for the effect to run just once. It also prevents having to write useEffect(..., []) all the time.

That's all folks!

Top comments (0)