Sale

The past few weeks have brought a lot of change all over the world. Here at Level Up, we hope you're taking appropriate actions to protect yourself and those around you from the spread of COVID-19. Because many of you are stuck at home, we've put all courses and the yearly subscription (Level Up Pro) 50% off until you unsubscribe.
Stay safe. - Scott Tolinski

Save 50%

$12/month*

*Paid annually

card background pattern
Level 2

Custom React Hooks

Unlock Full Course

$49.99 $24.99

Or

$24.99/Month

React Context & Custom Hooks

With React’s context we can share data easily without passing props through multiple children. Here we will take a look at the useContext hook and start making a robust hook to control our global state.

Downloads

Comments

dave.js
updated 2 months ago

@Jesse Burton This seems like a fine workaround to me, but a bit more verbose than using an array. Another way to namespace these to avoid collisions would be to not destructure them:

const first = useToggle(); 
const second = useToggle();
/* ... */
<button onClick={first.toggle}>First {first.isToggled && '(on)'}</button>
<button onClick={second.toggle}>Second {second.isToggled && '(on)'}</button>
Jesse Burton
2 months ago

So one other advantage that I can see to using an array is that you can easily have multiple instances of a custom hook in one component (i.e. multiple toggles) It seems that using an object would limit you to one instance since the variable names are already chosen.

One way that works to get around this would be to rename the variables:

const { isToggled: isToggledFirst, toggle: setToggledFirst } = useToggle(); const { isToggled: isToggledSecond, toggle: setToggledSecond } = useToggle();

Do you see any complications in doing it this way?

Something to say?

Become a Pro