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);
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);
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);
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!
🌎 Let's Connect!
- My Twitter: @thenaubit
- My Substack (here I publish more in-depth articles)
Top comments (18)
Your
useDebounce
hook doesn't work as you described. It behaves likesetInterval
: setsdebouncing
totrue
and triggers callback on initial render then resets it tofalse
afterdelay
, repeating the process. Same with youruseThrottle
hook. Did you test these?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!
@naubit they still don't work. You should remove them from your article so others aren't misled.
Plagiarism isn’t cool man
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.
use window in useeffect.
I'm totally using your
useDebounce
hook, thanks for sharing!Make sure to check the new one, I have updated it to the right one after the good call @bryce did!
For the
useWindowSize()
hooks, it's better to use a passive event listener:window.addEventListener("resize", handleResize, { passive: true });
this repo has all the above and more: github.com/streamich/react-use , highly recommend.
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 🤩
Great article @naubit
Thanks for sharing great article..
Why create one when you can get all awesome hooks in a single library?
Try scriptkavi/hooks. Copy paste style and easy to integrate with its own CLI
Lots of useful hooks, but Jeezy Creezy, could you make your headlines less clickbaity?