DEV Community

chantastic
chantastic

Posted on

5

Extract Custom Hooks

First, what's a Hook?

Hooks are the use-prefixed functions that we've been using — useState and useEffect.

Components are the primary building block of React.
Hooks are what give Components interactivity.

Hooks are composable

We've seen that hooks can be used together to accomplish discreet tasks.

let [componentValue, setComponentValue] = useState(null);

React.useEffect(() = {
  fetchNetworkValue(query).then(networkValue => setComponentValue(networkValue));
})
Enter fullscreen mode Exit fullscreen mode

You can make your own Hooks

Hooks can be extracted into functions just like Components.

function useRequest(query) {
  let [componentValue, setComponentValue] = useState(null);

  React.useEffect(() = {
    fetchNetworkValue(query).then(networkValue => setComponentValue(networkValue));
  })

  return componentValue;
}
Enter fullscreen mode Exit fullscreen mode

When we extract custom Hooks, we need to add the inputs and the outputs.

Inputs we take as function arguments.

Outputs we return from the function.

In the example above, we take query as a function argument and return componentValue.

The power is yours

You're not limited to one argument and return.
You can take many arguments and return any data type.

Explore! The world of Hooks is yours.

Try it out!

Open this Code Sandbox in your browser and explore custom Hooks.

Assignment Sandbox:

Assignment

  1. Declare a new function named usePokemon
  2. Take index as an argument
  3. Move the pokemon useState(null) hook and useEffect() Hooks into the body of that function
  4. Return pokemon from that function
  5. In App, call the new Hook usePokemon(index) and assign it's return to the variable pokemon

You've just made a custom Hook!


Follow the 🧵 on Twitter:

Subscribe on YouTube:

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay