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.
const initialState = {
name: 'John'
};
export default function userState (state = initialState, action) {...}
User.defaultProps = {
name:'John'
};
Which one is the best and why?
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'));
});
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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With