DEV Community

Discussion on: Using Redux with Classes and Hooks

Collapse
 
markerikson profile image
Mark Erikson

Hi, I'm a Redux maintainer. Got a couple quick bits of feedback for you.

First, I'd specifically encourage you to try out our new official Redux Toolkit package. It includes utilities to simplify several common Redux use cases, including store setup, defining reducers, immutable update logic, and even creating entire "slices" of state at once, without writing any action creators or action types by hand:

redux-toolkit.js.org

Second, there's actually at least one bug in your code examples, and RTK actually would have prevented it:

        case UPDATE_SONG:
            return {
                songs: state.songs.filter((song, i) => {
                    if(i === action.index) {
                         song.title = action.title
                        song.editing = false
                    }
                    return song
                })
            }

This reducer logic is mutating the existing song objects. It does create a new songs array, but the song object is being mutated. To be a correct immutable update, you'd need to copy song, like return {...song, title: action.title, editing: false}.

RTK includes a mutation checking middleware by default when you use its configureStore() function, which would have thrown an error after that mutation to let you know it happened.

But, with RTK's use of Immer in its createReducer and createSlice functions, that could have simply been:

updateSong(state, action) {
    const song = state.songs[action.payload];
    // "mutates" the song, but it's safe if we do that with Immer
    song.title = action.title; 
}

In addition, we would recommend using a "feature folder" or a "ducks" folder structure, as shown in the RTK "Advanced Tutorial" page, rather than a "folder by type" approach.

Hope that helps!

Collapse
 
john2220 profile image
John Raptis

Wow!!! Thanks for the feedback. Very interesting suggestions. I will definitely check out the RTK.

Cheers