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.jsfile, we have our customuseCounterhook. - built-in React useState hook is used to keep track of the
countervalue. - We set the initial value of the
counterby using aninitialCounterfunction parameter and if it's not provided, we use 0 as a default. handleIncrementandhandleDecrementhandlers are updating the value ofcounterusingsetCounterfunction.- IMPORTANT: We are relying on the previous value of the
counterwhile updating it, hence we use a function to access the previous state. - For simplicity, we are also exposing the
isDecrementDisabledboolean to disable the decrement button when the value of thecounteris 0. - Inside of the
App.jsfile, we are using our newly created, customuseCounterhook with 10 as an initialcountervalue and build AN ACTUAL application thanks to it which you could saw in the above preview. - How cool is that to build custom hooks? 😎
