card background pattern
Level 2

Custom React Hooks

Unlock Full Course

$49.99 $24.99



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.



updated 4 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
4 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