For example from this example:
export const ADD_TODO = 'ADD_TODO'
export const DELETE_TODO = 'DELETE_TODO'
export const EDIT_TODO = 'EDIT_TODO'
export const COMPLETE_TODO = 'COMPLETE_TODO'
export const COMPLETE_ALL = 'COMPLETE_ALL'
export const CLEAR_COMPLETED = 'CLEAR_COMPLETED'
It's not like you're saving characters. The variable name is exactly the same as the string, and will never change. I understand making constants if one day you were doing to do something like:
ADD_TODO = 'CREATE_TODO'
but that never happens. So what purpose do these constants serve?
Not related to redux but a useful tip for all react developers.
Consider this example:
Question: Why should I extract 'Missing value' to a constant?
Answer: Javascript is basically calling
new String('Missing value')
thus creating a new object for each item in the array and for eachrender()
execution. This is both unnecessary and depending on the array size can impact performanceThis is more useful in other languages, but also somewhat useful in JavaScript. For instance, if I used
"ADD_TODO"
throughout the code, instead ofADD_TODO
, then if I make a mistake typing any of the strings, if it was code like,if (action === 'ADD_TODOz')
, when that code executes, it will do the wrong thing. But if you mistyped the name of the const,if (action === ADD_TODOz)
, you'll get som kind of aReferenceError: ADD_TODOz is not defined
when that line attempts to execute -- becauseADD_TODOz
is an invalid reference. And, of course, in a static language, you'll get an error at "compile time."I would like to quote @dan_abramov, the author of Redux from a comment on similar Github issue.
Here's the link to the Github issue
You are right, it is not about saving characters however after code minification you can save some space.
In redux you use those constants at least in two places - in your reducers and during actions creation. So it's much convenient to define a constant once in some file e.g.
actionTypes.js
And then require it in actions creator file e.g.
actions.js
And in some reducer
It allows you to easily find all usages of that constant across the project (if you use an IDE). It also prevents you from introducing silly bugs caused by typos -- in which case, you will get a
ReferenceError
immediately.