Home > database >  Should I use useEffect in this situation?
Should I use useEffect in this situation?

Time:10-21

I don't know if I am allowed to ask questions like these, but I have a dilemma where I don't know should I use useEffect in the situation I have here:

const handleUrlQuery = () => {
    if (params.debouncedValue.length > 0) {
      queryName = "name";
      queryValue = params.debouncedValue;
      return {
        queryName,
        queryValue,
      };
    } else if (params.debouncedValue === "") {
      queryName = "page";
      queryValue = params.page;
      return {
        queryName,
        queryValue,
      };
    }
  };

  handleUrlQuery();

const url = `${process.env.REACT_APP_API_URL}?${queryName}=${queryValue}`;

const { data, error } = useFetch(url);

This function is used for changing the query part of the url, now it is supposed to change the queryName and queryValue based on the search value or in this case debounced search value. Now I am confused because I have a feeling that I need to use useEffect, but I am not sure, anyone has any advice on this?

CodePudding user response:

When you don't call the function handleUrlQuery inside a useEffect, it will be called on every re-render, even if params.debouncedValue didn't change.

Therefore, you need a useEffect if you have other state variables changing, and you only want to call handleUrlQuery when specifically params.debouncedValue changes.

Dummy Codesandbox example

CodePudding user response:

If you really want to optimize this code, which unless its in a super heavy component, I don't see too much of a need you could use useMemo.

const url = useMemo(() => {
    if (params.debouncedValue.length > 0) {
      queryName = "name";
      queryValue = params.debouncedValue;
    } else if (params.debouncedValue === "") {
      queryName = "page";
      queryValue = params.page;
    }
    return `${process.env.REACT_APP_API_URL}?${queryName}=${queryValue}`;
  }, [params.debouncedValue, params.page]);
// don't believe you have to add process.env.REACT_APP_API_URL as a dependency

const { data, error } = useFetch(url);
  • Related