useEffect.dev
← Back to lessons

Lesson 3. Custom hooks and classic async pattern 2. Creating custom hooks

As you can extract some code into functions to make it reusable, you can create new hooks calling React's hooks. The only constraint is that you must name a hook with the use prefix.

Here what it can look like for our need:

Result

This custom hook returns the three values loading, error, and starship as an object so we can use them in our rendering, but there is no more way for us to update them, which is nice since we don’t have to update them manually: we hid this logic in the custom hook.

export const Starship = ({ starshipId }) => {
const { loading, error, starship } = useStarship(starshipId)
// ...rendering
}

It is not the case here, but if your use case requires the consumer of your hook to be able to update these values, you can return the setters as well:

const useStarship = (starshipId) => {
// ...
return {
loading, setLoading,
error, setError,
starship, setStarship,
}
}

Now, any other component can use useStarship to do what it wants with the returned value—an excellent way to extract component logic outside of the rendering concern.