challenges

Next.js Data Fetching: Part 5

Workshop context

Before this workshop

  • In previous workshops, we created an endpoint and executed a fetch call to the endpoint upon button click. We also managed the loading and error states.

This workshop

  • In this workshop, we’re going to move the fetch and state logic a custom hook, so the Home component in page.tsx remains high-level: someone reading the component can get a big-picture view without having to read all the details.

After this workshop

  • In the next workshop, we’ll update the UI to conditionally display a loading spinner, the quote card, or an error card, depending on the state values.

Workshop goal

By the end of this workshop you will have a custom hook called useQuoteStyles that:

  • abstracts the state and data fetching logic from page.tsx.
  • returns an object that includes all state values and the handleClick function. You should rename the handleClick function to something that indicates what the function does, for better readability.

Hints

Hint 1 Start by creating a file for the custom hook. You might create it in src/hooks/use-quote-styles.ts.

Hint 2 Create a function called useQuoteStyles in use-quote-styles.ts (all hooks start with use ). Then move all the state and the handleClick function from page.tsx to useQuoteStyles.

use-quote-styles.ts

// imports
 
function useQuoteStyles() {
  // state and logic here
 
  // return state and renamed handleClick function
}
 
export default useQuoteStyles;

Hint 3 You can destructure the state and renamed handleClick function (I renamed it fetchQuoteStyles) from the useQuoteStyles return value:

page.tsx

import useQuoteStyles from "@/hooks/use-quote-styles"
// ...
 
export default function Home() {
  const { status, error, quote, fetchQuoteStyles } = useQuoteStyles();
  // ...
}

Resources