Create a custom hook for managing timers in React or React Native
While trying to build a “simple” (I hate that word) Pomodoro app and banging my head against the wall trying to get moment.js
to play nice with React Native, I stumbled into creating a solution and thought I’d share it!
The hook is Typescript friendly and works on both React and React Native.
Installation
The implementation steps are further down in the post, but if you’d like to install the hook into your project rather than implementing it yourself you can find the installation and usage steps on the GitHub repo
- make sure you are in your project folder. check out expo-cli for React Native or create-react-app for React if you aren’t familiar with how to scaffold a new app
yarn add moment
yarn add use-moment-countdown
Usage
Implementation
If you’d like to implement your own version of the hook, and maybe customize it for yourself you can opt to implement it in your own project. Here’s how:
This hook relies on the very useFul (hehe — hook pun 🤦♂) useInterval
hook made by Dan Abramov.
Here’s the implementation for useCountdown
.
Links
- Check out the repository
- See a live example
- Also a huge thank you to Herman Starikov for create-react-hook. I used it to deploy this hook to npm and the process was super smooth. Herman wrote a medium article on it if you’re curious.
If you notice any issues or would like to give feedback/feature requests I appreciate it!
I hope it saves you some time!