How can I simplify my reducer function or how long should a simple reducer function be?

I have a reducer function whose sole purpose it to toggle a style on and off. This is a global style and this is why it is in my Redux store.

However, the code looks overly obtuse for such a simple toggle.

const Style = (state = {current: true}, action) => {
  if(action.type === "toggleAppStyle"){
    const newState = { ...state };
    newState.current = !state.current;
    return newState;
  }
  return state;
};

I recently realized that redux runs all reducer functions for each single action, which I find strange, so the returned state must equal the initial state if the action.type is not called for that particular reducer.

Here is the one place I use it:

// ... snip
const mapStateToProps = state => {
  return {
    Style: state.Style
  }
}
  
  // ... snip
  render() {
    return (
      <img className = 'icon_all' 
           id = {this.props.Style.current === true ? 'icon_10' : 'icon_90'} 
           onClick = {this.clickHandler} src='/images/favicon-optimized.svg'/>
    )
  }

Answer

the code looks overly obtuse for such a simple toggle.

Overly obtuse is a bit much, this is a pretty standard immutable update pattern, i.e. shallow copy into new object reference and update the necessary properties.

It can’t get much simpler than what you’ve already got, but here is an example returning the new object directly.

const Style = (state = {current: true}, action) => {
  if (action.type === "toggleAppStyle") {
    return {
      ...state,
      current: !state.current,
    };
  }
  return state;
};

I recently realized that redux runs all reducer functions for each single action, which I find strange, so the returned state must equal the initial state if the action.type is not called for that particular reducer.

Nothing strange here really. The reducer function either acts on the action and operates on the state, thus returning a new state reference and value, otherwise it simply returns the current state value. Other than the action part this is exactly how React reconciliation works. When you update state you are creating new object references or primitive values. This is what triggers rerenders.

Of course, if your objective is to be as short and succinct as possible, you could reduce the state slice to just the boolean value and use a ternary operator to return the toggled state or current state value. Adjust your redux selectors accordingly.

const Style = (state = true, action) => action.type === "toggleAppStyle"
  ? !state
  : state;