Learn How To Build Custom Hooks in React
2 October, 2022
4
4
0
Contributors
What is a custom hook?
A custom Hook is a JavaScript function whose name starts with "use
" and that may call other Hooks.
They are reusable functions. Both components and hooks are functions.
Why do I need a custom hook?
Building your own hooks allows you to extract component logic into reusable functions. When we want to share logic between two JavaScript functions, we extract it to a third function.
Building our custom hook
Let’s say we fetch data in our Joke
and User
components from an API using the fetch()
method. We can typically write our components like this:
We can see the fetch()
logic is needed in both components, so we can extract the fetch logic into a custom hook that’ll be used by both components.
Then, we can update our Joke
and User
components respectively.
We have created a new file called useFetch.js
containing a function called useFetch
which contains all of the logic needed to fetch our data.
We removed the hard-coded URL and replaced it with a url
variable that can be passed to the custom Hook. Lastly, we are returning our data from our Hook.
In Joke
and User
, we are importing our useFetch
Hook and utilizing it like any other Hook. This is where we pass in the URL to fetch data.
Now we can reuse this custom Hook in any component to fetch data from any URL.😎
FAQ 🤔
-
Is the
useFetch
equivalent to the originalfetch()
in ourJoke
?Yes, it works in exactly the same way. If you look closely, you’ll notice we didn’t make any changes to the behavior. All we did was extract some common code between two functions into a separate function
-
Do I have to name my custom Hook starting with “use”?
Please do, why?
Without it, we would not be able to check for violations of rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it.
-
Do two components using the same Hook share the same state?
No. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all states and effects inside of it are fully isolated.
-
How does a custom Hook get an isolated state?
Each call to a Hook gets an isolated state. Because we call
useFetch
directly, from React’s point of view our component just callsuseState
anduseEffect
.
Extra Custom Hooks
useAxios
useAsyncAwait
react
javascript
reacthooks