Redux Tutorial: Color Switch App

I couldn’t find any good tutorials for beginners when I was learning Redux so I made one. It’s a simple color switch app that changes the color of the background when you click on buttons but I thought it’ll be nice to learn from something other than a counter or todo list. Let me know what you guys think of it!
Link to Guide: https://link.medium.com/u6pd0I8iIU

// Set initial state as object with t
ype color white
const initialState = {
  color: 'white'
}

//-----------------
// 1. REDUCER
//-----------------
// Create a Reducer that takes in state and action as arguments and returns a new state
// In ES6, state takes in initialState whenever state is undefined
// State is immutable
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'RED':
      return { ...state, color: 'red' };
    case 'BLUE':
      return { ...state, color: 'blue' };
    case 'GREEN':
      return { ...state, color: 'green' };
    case 'YELLOW':
      return { ...state, color: 'yellow' };      
    default:
      return state;
  };
}

//-----------------
// 2. STORE
//-----------------
// Create a Redux store to manage state
// Declare a store variable and assign it to the createStore() method
const store = Redux.createStore(reducer);
console.log('[Store]', store.getState());
// -> [Store] { color: 'white' }

//-----------------
// 3. SUBSCRIBE
//-----------------
// Subscribe takes a function that will be executed whenever the state is updated
store.subscribe(() => {
  console.log('[Subscribe]', store.getState());
});


//-----------------
// 4. DISPATCH
//-----------------
// Dispatch action
// An action contains information and sends it to your Redux store
// Here the action is an object with a type property
store.dispatch({ type: 'RED' });
console.log('[Dispatch]', store.getState());
// -> [Subscribe] { color: 'red' }
// -> [Dispatch] { color: 'red' }

// Create a React component that has props value, redSwitch, blueSwitch, greenSwitch, yellowSwitch
const Color = ({ 
  value,
  redSwitch,
  blueSwitch,
  greenSwitch,
  yellowSwitch
}) => (
  <div className={value}>
    <button onClick={redSwitch}>Red</button>
    <button onClick={blueSwitch}>Blue</button>
    <button onClick={greenSwitch}>Green</button>
    <button onClick={yellowSwitch}>Yellow</button>
  </div>
);

// Create a function render that renders React component to the Dom
const render = () => {
  ReactDOM.render(
    <Color 
      value={store.getState().color}
      redSwitch={() => store.dispatch({
        type: 'RED'
      })}
      blueSwitch={() => store.dispatch({
        type: 'BLUE'
      })} 
      greenSwitch={() => store.dispatch({
        type: 'GREEN'
      })} 
      yellowSwitch={() => store.dispatch({
        type: 'YELLOW'        
      })}
    />,
    document.getElementById('root')
  );
}

// Subscribe render function to the store
store.subscribe(render);

// Call render to render the state
render();
1 Like

I like the article. Been trying to wrap my mind around reducers for a while now, and this helped a lot. What do you think about redux vs hooks?

I haven’t started on hooks yet! I’m taking it one step at a time with React and I want to make sure that I understand each concept thoroughly before moving on. I know that hooks are used to give function (“stateless”) components state and I don’t need them for now because I turn my components into class components (“stateful”) if they have state. Hooks would be more useful for someone with an existing project and complex architecture. I might use it in the future. My approach is to only learn something if I need it :slight_smile:

I look at hooks and think of ones like useReducer as more complementary to redux rather than replacing it. What that particular hook might do is replace react-redux, but even so I don’t think it could do so all by itself. It could replace the connect() function, since it effectively replaces mapState and mapDispatch, but there’s still the problem of how you get the reducer to the component in the first place. That’s something <Provider> does for you, but there’s no equivalent in hooks. Contexts could possibly do the trick, but I don’t find them appealing.

Hooks still look awesome, but they look like primitives to build more robust solutions on, not a framework unto themselves.

Pop quiz: what react-redux uses behind the scenes?

Sure, it uses contexts, but they’re hidden from you. Going back to using contexts by hand is what I object to.

Well, since Context got out of “unstable, do not use!!!” state, it’s pretty usable.

But, anyway, redux is not going away any time soon (although I’ve heard that for new projects it’s not the first choice).