How To Create A Custom React Hook

React

18/09/2021


First off, what is a custom hook? It's nothing more than a function that uses another React hook. If it doesn't use one, then it's simply a helper function.

It's common practice to prepend use to the function name. While it serves no technical ⚙️ purpose, it helps your linter warn for errors.

Example hook

To demonstrate just how simple and easy it is for a function to qualify as a hook, here's a an example:

JAVASCRIPT
const useNumber = (number) => {
const [someNumber] = useState(number)
return someNumber
}

Probably the most useless hook you've ever seen, 😅 but it perfectly demonstrates the point I want to get across: you need to use at a minimum 1 single hook.

It doesn't matter what you return. It may be a single value, an array, an object or even nothing at all.

JAVASCRIPT
const number = useNumber(10)
console.log(number) // 10

WRITTEN BY

Code and stuff