Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
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? 😎
logo with a rocket of the BigDevSoon application

Level up your Frontend skills

Code real-world projects based on Figma designs.
spread the word
Did you like this post? Share it with the world! 🌐