0

Here's my sample code:

const { getConversionList, conversionList } = useConversion();

useEffect(() => {
  getConversionList();
}, []);

useConversion is a GraphQL resolver hook, I'm getting Linting error to add dependency. But if I add dependency then it is an infinite rendering.

How can I safely bypass it?

Tried adding dependency by caused infinite rendering. I want useEffect to run only once on load hence added [] as dependency

6
  • Do you really need this useEffect? you can try useEffect(() => { getConversionList(); }, [getConversionList]); if you need it on initial rendering will be something like this I guess const { conversionList, loading, error } = useConversionsList(); Commented Jul 3 at 15:38
  • @ZhivkoNikolov but in that case on every re-render that useConversionList() function would be called, not only on initial rendering Commented Jul 3 at 15:52
  • if you haven't wrapped your "getConversionList, conversionList" inside the useMemo hook. can you wrap it
    – Vinoth
    Commented Jul 3 at 17:13
  • You Might Not Need an Effect
    – Arkellys
    Commented Jul 4 at 5:09
  • well then you will need cache setup, so the data will be fetched only when needed apollographql.com/docs/react/caching/overview Talking from experience: reading the Docs can save you a lot of time Commented Jul 4 at 7:04

4 Answers 4

0
  1. Disable the linting rule for this specific line.
  2. Use a ref to store the function so it doesn't change on each render.
import { useEffect, useRef } from 'react';
const { getConversionList, conversionList } = useConversion();
    
const getConversionListRef = useRef(getConversionList);
    
useEffect(() => {
  getConversionListRef.current();
}, []);
0

You may try add this below line. // eslint-disable-next-line

For your code snippet.

const { getConversionList, conversionList } = useConversion();
useEffect(() => {
  getConversionList();
// eslint-disable-next-line
}, []);
0

You can ensure that useEffect runs only once by using a useRef hook to track if the effect has already run:

const { getConversionList, conversionList } = useConversion();
const hasFetchedRef = useRef(false);

useEffect(() => {
  if (!hasFetchedRef.current) {
    getConversionList();
    hasFetchedRef.current = true;
  }
}, [getConversionList]);
0

Created a custom hook like this and used it to resolve. I see several articles on it

import { useEffect } from "react"

export default function useEffectOnce(cb) {
    useEffect(cb, [])
}

useEffectOnce(()=>{
  getConversionList();
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.