Home > Software engineering >  React Custom Hook function keeps recalling
React Custom Hook function keeps recalling

Time:05-12

According to the thread below,

useCustomHook being called on every render - is something wrong with this

It says it is completely normal to keep calling the custom hook function every time React re-renders.

My questions are, if it affects on a performance side when returning an array from this Custom Hook function( Not when fetching API and receiving data ) which contains a lot of values.

If so, how to prevent it ( How to let this Custom Hook function run only once )?

Here is my Custom Hook code, it returns an array which contains around 5000 string values.

function FetchWords(url: string) {
  const [data, setData] = useState<string[]>([]);

  useEffect(() => {
    fetch(url)
      .then((words) => words.text())
      .then((textedWords) => {
        setData(textedWords.replace(/\r\n/g, "\n").split("\n"));
      });
  }, []);
  const expensiveData = useMemo(() => data, [data]);
  return expensiveData;
}

export default FetchWords;

My Main js

const wordLists: any[] = useFetch(
    "https://raw.githubusercontent.com/charlesreid1/five-letter-words/master/sgb-words.txt"
  );

CodePudding user response:

  1. If you are worried about bringing all this data at the same time, you can indicate from the backend that they send you a certain number of records and from the frontend you can manage them with the pagination.
  2. the use of useMemo is superfluous.
  3. the useEffect that you are using will only be rendered ONCE, that is, it will only call the 5,000 registers that you mention only once

CodePudding user response:

  1. CustomHooks should start with word use...
  2. You don't need useMemo in your hook, simply return data state.
  3. Your hook makes the fetch call only once, so no problem there as the effect has empty dependency, so it runs once after first render.
  4. The hook stores the array of 5000 entries once in data state and returns the same reference each time your custom hook is called during component re-renders. There is no copy operation, so you don't need to worry about that.
  5. If you only want to fetch 100 entries for example, then your backend needs to provide that api.

Hope this resolves your queries as it is not very clear what is your doubt.

  • Related