skip to Main Content

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

3

Answers


    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();
    }, []);
    
    Login or Signup to reply.
  1. 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
    }, []);
    
    Login or Signup to reply.
  2. 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]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search