r/reactjs • • Oct 30 '17

Beginner's Thread / Easy Questions (week of 2017-10-29)

Looks like the last thread stayed open for quite a while, and had plenty of questions. Time for a new thread! (I should probably consider labeling these as monthly or something :) )

Soo... Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch. No question is too simple.

The Reactiflux chat channels on Discord are another great place to ask for help as well.

22 Upvotes

145 comments sorted by

View all comments

Show parent comment

4

u/acemarke Nov 16 '17

Yeah, my ("our"?) standard advice is to focus on learning React first. Once you're familiar with React, then you'll generally have a better understanding of why a state management lib like Redux can be useful, and how the pieces fit together.

redux-actions is a neat little lib, but as Dan Abramov said a few months ago:

Dan Abramov, just now : "if you want to teach someone why to use an abstraction, you should first make them feel the pain of not having it"

Might be worth not using redux-actions at first and writing out actions, action creators, and reducers yourself so you see the way they're used together.

The "multiple reducers responding" behavior generally comes into play with slice reducers. Here's a 100% completely un-tested example of how this might work using redux-actions:

import { createAction, handleActions } from 'redux-actions';
import {combineReducers, createStore} from "redux";

const increment = createAction("INCREMENT");

const countByOne = handleActions({
    [increment] : (state, action) => state + 1
}, 0);

const countByFive = handleActions({
    [increment] : (state, action) => state + 5
}, 0);

const rootReducer = combineReducers({
    counter1 : countBy1,
    counter5 : countBy5,
});

const store = createStore(rootReducer);

store.dispatch(increment);
console.log(store.getState());
// {counter1 : 1, counter5 : 5}

So, both the counter1 and counter5 slice reducers are responding to the "INCREMENT" action, separately, and as appropriate for their own slice of state.

You might want to check out my "Practical Redux" tutorial series. It assumes you know the basics, and shows some examples of how to build a somewhat more "real-world-ish" type app.

2

u/Awnry_Abe Nov 18 '17

Excellent pattern. I refactored the store to follow the shape you present and now I feel like I have a clean line of sight for the full app model. I only had 2 full routes worth of container components to touch, and this shape shift exposed yet another weakness in my pattern that was easily fixed with yet another new discovery: Selectors! I knew of them, but changing my store around made their purpose obvious.