DEV Community

Cover image for 5 Custom React Hooks That Will Transform YourCode
Al - Naubit
Al - Naubit

Posted on


5 Custom React Hooks That Will Transform YourCode

Yesterday after finishing my daily article (yeah, I publish a new article about front-end development every day, so make sure to follow if you want a daily pill of code ), I went to code for a little and... I started coding some custom hooks for a side project I am building (I am talking about it on my Twitter: @thenaubit).

I realized there are lots of really useful custom React hooks. So I am starting a new series where I will post some of those (coded by me or found on the Internet and converted to TypeScript).

And if you have done one that you are proud of, feel free to share a gist link in the comments, and I will add it to the following article!

1儭 useWindowSize Hook

I am pretty sure you have needed to get the width and height of the user's window in some projects you have worked on.

Well, now you have a hook for that, so you can do it even easier than before!

This hook can be particularly useful when implementing responsive design, and for some reason, you need to run some specific code in some resolutions!

2儭 useKeyPress Hook

The next hook lets you detect when a specific key is pressed. This can trigger events or actions based on the key pressed. For example, for closing a modal, submitting a form... you know, there are lot of options.

Of course, I will give you an example of how to use it:

const closeModalKeyPress = useKeyPress("Escape");

Yeah, it is that easy.

3儭 useInterval Hook

This hook allows you to use the famous setInterval function as a hook! Like the setInterval function, this hook has many uses, like animations, updating data at regular intervals, or even setting a timer.

You can use this hook like this:

const [count, setCount] = useState(0);

useInterval(() => {
  setCount(count + 1);
}, 1000);
Enter fullscreen mode Exit fullscreen mode

4儭 useDebounce Hook

Now we will talk about one for debouncing functions. If you don't know what it is, basically the function will only be executed after a certain amount of time has passed without it being called.

This is useful, for example, for rate-limiting API calls or state updates on input changes, like when you are typing some text in a search input.

A usage example would be:

const [inputValue, setInputValue] = useState("");

useDebounce(() => {
// make API call
}, 500);
Enter fullscreen mode Exit fullscreen mode

5儭 useThrottle Hook

The previous one was a debounce hook, and now it is the turn of a throttle hook.

As its name says, it is a hook to throttle a function. It means it will be executed once per every specified interval of time. This can be useful for preventing too many API calls or events from being triggered in rapid succession.

An example would be:

const [inputValue, setInputValue] = useState("");

useThrottle(() => {
// make API call
}, 500);
Enter fullscreen mode Exit fullscreen mode

Well, we reached the end of the article, but before you go, I want to say a few extra key things.

The first one is these hooks are examples, just like any other code you find on the Internet. You should not just copy and paste them into your project. You should read them, understand them and improve them!

With that being said, I really enjoy writing this kind of article, so if you also like them, make sure to follow and like them. That way, I will know people want more, and we will have more. Oh, and as I said at the beginning of the article, if you have some little hooks you like, share them here; I want to add them in the next post!


Top comments (18)

bryce profile image
Bryce Dorn

Your useDebounce hook doesn't work as you described. It behaves like setInterval: sets debouncing to true and triggers callback on initial render then resets it to false after delay, repeating the process. Same with your useThrottle hook. Did you test these?

naubit profile image
Al - Naubit

Thanks for making me double check; they were indeed wrong. I copied them from a really old project I had and they were not right. Now I have updated them to the right ones, ty!

bryce profile image
Bryce Dorn

@naubit they still don't work. You should remove them from your article so others aren't misled.

cleveroscar profile image
Oscar Ortiz

Plagiarism isnt cool man

sureisfun profile image
Barry Melton

To anyone considering using the windowSize hook in an SSR project, note that use of window will be a challenge that you'll either need to wrap in try/catch or prototype an empty window to use in SSR.

Also having had an old project that used them extensively, they tend to be a lot more problematic than (e.g.) just using CSS and media queries.

charlie007star profile image
Sujin S R

use window in useeffect.

travelingwilbur profile image
Wilbur Suero

I'm totally using your useDebounce hook, thanks for sharing!

naubit profile image
Al - Naubit

Make sure to check the new one, I have updated it to the right one after the good call @bryce did!

yimiprod profile image

For the useWindowSize() hooks, it's better to use a passive event listener:
window.addEventListener("resize", handleResize, { passive: true });

tonnoz profile image

this repo has all the above and more: , highly recommend.

creativemacmac profile image

This is BRILLIANT i have been searching high and low for a react hook to work with keyboard press so am of course loving this post. Thank you so much 予

kumarkalyan profile image
Kumar Kalyan

Great article @naubit

codeofrelevancy profile image
Code of Relevancy

Thanks for sharing great article..

georgewl profile image
George WL • Edited

Lots of useful hooks, but Jeezy Creezy, could you make your headlines less clickbaity?

1ayman13 profile image

.....great.How can I transform your work to python?

opendataanalytics profile image
The Open Coder

Great article on custom React hooks! These hooks simplify the process of adding functionality and make the code much more readable.

aboutcb1 profile image


Visualizing Promises and Async/Await

async await

儭 Check out this all-time classic DEV post on visualizing Promises and Async/Await