Skip to content

Instantly share code, notes, and snippets.

@markusra
Last active March 20, 2019 16:22
Show Gist options
  • Save markusra/56c8c7cfa1a94c9105b64eb6261d6301 to your computer and use it in GitHub Desktop.
Save markusra/56c8c7cfa1a94c9105b64eb6261d6301 to your computer and use it in GitHub Desktop.

Custom Hooks

Definition

A custom Hook is a JavaScript function whose name starts with use and that may call other Hooks.

When to use

Custom Hooks can be used when we want to reuse some stateful logic between components.

Important to know

  • Your should name your custom Hooks starting with use (need it in order to check if you follow the the rules of Hooks)
  • Two components using the same custom Hook do not share any state (they only share stateful logic)

Example

Here is a simple example of a custom Hook for a rocket's takeoff status:

import React, { useState, useEffect } from 'react';

function useReadyForTakeoffStatus(rocketID) {
  const [isReadyForTakeoff, setIsReadyForTakeoff] = useState(null);

  useEffect(() => {
    const handleStatusChange = (status) => {
      setIsReadyForTakeoff(status);
    }

    handleStatusChange(SpaceXAPI.getStatus(rocketID));
  });

  return isReadyForTakeoff;
}

We can use the custom Hook, useReadyForTakeoffStatus like this:

const ReadyForTakeoffComponent = ({ rocketID }) => {
  const isReadyForTakeoff = useReadyForTakeoffStatus(rocketID);

  return (
    <div>
      The rocket is {!isReadyForTakeoff && 'not yet'} ready for takeoff.
    </div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment