loading...

Extract Custom Hooks

chantastic profile image Michael Chan ・1 min read

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));
})

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;
}

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:

Discussion

pic
Editor guide