Image by Veri Ivanova from Unsplash
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
Summary
- Inside the
useCounter.js
file, we have our customuseCounter
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 aninitialCounter
function parameter and if it's not provided, we use 0 as a default. handleIncrement
andhandleDecrement
handlers are updating the value ofcounter
usingsetCounter
function.- IMPORTANT: We are relying on the previous value of the
counter
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 thecounter
is 0. - Inside of the
App.js
file, we are using our newly created, customuseCounter
hook with 10 as an initialcounter
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? 😎