Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Discover Mentorship
The above is an affiliate link, if you buy the book I'll get a small commission at no extra charge to you.
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
The above is an affiliate link, if you buy the book I'll get a small commission at no extra charge to you.
Home/Pills/ Pill - React counter hook/
Home/Pills/Pill - React counter hook/
Image by Veri Ivanova from Unsplash

React counter hook

Jan 21, 2021

DESCRIPTION

Let's create a custom hook for tracking the counter state and exposing the current counter value with increment, decrement handlers.

Preview

Tik, Tok, Tik, Tok

React
React

Summary

  • Inside the useCounter.js file, we have our custom useCounter hook.
  • built-in React useState hook is used to keep track of the counter value.
  • We set the initial value of the counter by using an initialCounter function parameter and if it's not provided, we use 0 as a default.
  • handleIncrement and handleDecrement handlers are updating the value of counter using setCounter function.
  • IMPORTANT: We are relying on the previous value of thecounter while updating it, hence we use a function to access the previous state.
  • For simplicity, we are also exposing the isDecrementDisabled boolean to disable the decrement button when the value of the counter is 0.
  • Inside of the App.js file, we are using our newly created, custom useCounter hook with 10 as an initial counter value and build AN ACTUAL application thanks to it which you could saw in the above preview.
  • How cool is that to build custom hooks? 😎
THE GUIDE TO BEAT FRONTEND INTERVIEW
From time to time, I'll send you messages about new blog posts, knowledge pills, and mentoring promotions. Only valuable information, no spam included. You can unsubscribe at any time.
slack
Let's build a community that will help each other.
spread the word
You don't need to, it's okay...