MAL's Logo

Custom hook (data requests)

💡 Three separate examples on how custom hooks can be used throughout a React application.

Introduction

The first example (option i) is a basic set up on how to fetch data. The second example (in codesandbox) allows parameters to be passed and thereby can be reused more easily with different endpoints. The third example (option ii) lets you pass parameters and utilise the returned object.

Code

Option I

// useHook.tsx
export const useDataHook = () => {
  const [isLoading, setIsLoading] = React.useState(true);
  const [data, setData] = React.useState<Character[]>([]);

  React.useEffect(() => {
    fetch("https://hp-api.onrender.com/api/characters")
      .then((response) => response.json())
      .then((data) => {
        setIsLoading(false);
        setData(data);
      });
  }, [setData]);

  return { isLoading, data };
};

// Main.tsx
const { isLoading, data } = useDataHook();

Option II

export const useBuildObject = () => {
  return React.useCallback((isARealBoy: boolean, title: string) => {
    const params = {
      id: 3434,
      isARealBoy,
      title
    };

    return params;
  }, []);
};

const buildObj = useBuildObject();
const params = buildObj(true, "Pinocchio");
console.log(params);

Resources

  • https://beta.reactjs.org/reference/react/useCallback
  • https://beta.reactjs.org/learn/reusing-logic-with-custom-hooks
  • MAL's Logo© 2021 – 2026 MAL. All rights reserved.