DEV Community

chantastic
chantastic

Posted on

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:

Top comments (0)