Passing state with React Hooks

Dustin Morris
2 min readAug 12, 2020

React Hooks are a recent addition to React. They allow state without using classes. Although classes are still supported, the general consensus is to migrate towards React Hooks.

My first foray using React Hooks was working on an open source project called Musyn (https://github.com/d-rowe/musyn) started by former music teacher and current React extraordinaire Daniel Rowe.

My challenge was simple: add a selector button for multiple instruments. The simple approach would have been to add a menu drop down. But I wanted to challenge myself and I also wanted to keep the same look and feel of the application and/or increase the UX.

I decided on a button that matched the current buttons in the navbar that would produce a pop-up with a circular navigation menu with icons for each instrument organized by brass, woods, percussion, etc.

The basic structure of the React modules were like this:

Module Flow Diagram

The top level function renders with this code:

Top level module— Requires state controlled by child modules

Passing state from a React class usually involves passing it through each subsequent child through the props parameter. With a function that modifies the parent class state, the parent class renders and subsequent children render allowing siblings to interact through the parent class.

However, useReducer is a built-in React Hook that I was able to use at the top level. useReducer returns an array of two variables. The first is the state and the second is the dispatch function similar to the Redux dispatch function.

All I needed to do is pass this dispatch function to the Tone Button to control the state variable need to make the <div> for Tone Selector visible. The behavior is now identical to the class based behavior of React.Component but using classless functions and React Hooks.

If you are wondering what toneReducer looks like. It is a simple function that handles the conditional logic needed to change the isOpen state.

Reducer Function is the conditional logic needed to change the state

--

--