In React, custom hooks have the purpose to group the logic related with the state and effects (useState,useEffect and another hooks) so this way the rest of the component (mostly jsx) consumes the data bring by the custom hook. Today, we take a look on this approach by implementing a timer component.
Our component looks like this:
This component is compose by two components more, a <TimerDisplay/>
(blue box) and a <TimerControls/>
(orange box)
Now, take a detailed look to their respectives codes:
<App/>
code looks like this.
You notice both the state-effects logic and the jsx are within the component <App/>
this is ok but think a moment if our Timer component requires more features is quite likely that state-effects logic grows and ofcourse the jsx too and yes, this becomes in a code hard to read, maintain and scale. And that's not all, make zoom at the return statement:
Like you see, the <TimerControls/>
has the prop setTimer
, and means this uses the state update function directly.
Don't be scared, it's just a simple component with a few handlers in it, but yes, you guessed it, if the parent component grows <TimerControls/>
will too.
So the solution is separate the state-effects logic and handlers and implement them through a custom hook. In this case, our custom hook gonna be useTimer()
. Is mandatory add the word use before the hook name this way React knows that the component uses a hook.
useTimer()
code looks like this.
In this case useTimer()
imports the handlers cause each one requires the setTimer()
(if you have a handler that doesn't update the state, the handlers can be consume by the component itself and not the custom hook). The new handlers code looks like this.
The one million question is how <App/>
consumes useTimer()
? Make zoom again but now at the useTimer()
return statement:
useTimer()
returns an object with timer (the state), alarmRef (it's just a ref attatched to an <audio>
tag that plays when timer comes to zero) and the handlers (setMinutes
, playOrPauseTimer
and resetTimer
). About the last ones note that are functions that returns another functions (the handlers imported) aka closures, now see how the components look like:
<App/>
<TimerControls/>
Conclusions
- If you think that your components code gonna grow, separate the state-effects logic and handlers through a custom hook.
- If your components handlers require update the state use them within a custom hook.
- Don't forget the use word before name your hook.
- Some React experts think that React more than an UI library is a mental model, so the most important hook that you can use is
useYourImagination
Final notes
- You can find the code at Github
- Or if you prefer the new Github web editor
Top comments (0)