Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Redux initialState vs defaultProps

I'm looking for the best practices of defining default props for Containers (which is smart components connected with redux store), and I find out that there are at least two approaches how I can realize it.

  1. To use initialState in my reducer:
const initialState = {
  name: 'John'
};

export default function userState (state = initialState, action) {...}
  1. To use defaultProps
User.defaultProps = {
  name:'John'
};

Which one is the best and why?

like image 637
WebBrother Avatar asked Jul 13 '16 11:07

WebBrother


3 Answers

You should use the initial state. The concept behind redux and every other library managing the application state is the strict separation of data/model and view. These concepts make it easier to reason about your code, reuse views and test both independently.

If you are using redux I would recommend managing you data (and your default data) inside of redux.

Example of separated test cases:

test('state test', t => {
    t.deepEqual(userState(undefined, { type: '@@INIT' }), { name: 'John' });
    t.deepEqual(
        userState({ name: 'John' }, { type: 'SET NAME', name: 'Isa' }),
        { name: 'Isa' }
    );
});

test('view test', t => {
    t.true(render(<User name="John" />).text().includes('John'));
});
like image 194
Herku Avatar answered Oct 25 '22 03:10

Herku


I think you misunderstood two different concepts.

Props in containers/components is just a way to tell component how it should looks or handle some events. But default props shouldn't contain business logic and shared business data, like userInformation.

If you have data like userInformation, which important not only for User container, but also can be useful for other components, store that information only in store.

like image 34
steppefox Avatar answered Oct 25 '22 01:10

steppefox


This explanation helped me to really get the difference between props and state, so I'll leave this here.

Dan Abramov, the creator of Redux, put it this way on Twitter, if I remember correctly:

Should I use component state to store X?

  • If I can calculate X from props -> No.
  • If I am not using X in the render method -> No.
  • Else -> Yes.

Dan was talking about component state here, rather than defaultProps, but the principle in this case is the same.

The point of Redux is to have a single source of truth for your application state. So in your example you would want to store your default values (like name: John) in the Redux store. Props are always passed from the store, but if you specify defaultProps, then you're storing application state outside of the store; it won't be managed by your reducer.

like image 3
Michael Helvey Avatar answered Oct 25 '22 02:10

Michael Helvey