Here's an exercise I wanted to share as part of my own efforts in learning out loud.
As part of a React project I'm working on, I needed to create and array containing the dates for the current month.
While composing the function I realized I would need to perform arithmetic on date objects. I could use the JS Date object directly, or I could make use of the methods provided by the moment.js library.
Moment.js
Implementing my function using the addon library allows use of the add method to increment a date. In the function below, day is a moment.js object.
function calendarDays(day) {
const days = []
day.date(1)
day.add(-(day.day() + 1), "d")
for (let i = 1; i <= 42; i++) {
day.add(1, "d")
days[i] = { day: day.date(), month: day.month() }
}
return days
}
The function is called from the component and the array rendered using using the following code:
{calendarDays(moment()).map(day => <span key={day.day} className="calendar-day">{day.day}</span>)}
The React profiler tool shows that the component renders in 2.2ms.
Javascript Object
function calendarDaysJS(day) {
const days = []
day.setDate(1)
day.setDate(1 - day.getDay())
for (let i = 1; i <= 42; i++) {
days[i] = { day: day.getDate(), month: day.getMonth() }
day.setDate(day.getDate() + 1)
}
return days
}
{calendarDaysJS(new Date()).map(day => <span key={day.day} className="calendar-day">{day.day}</span>)}
The React profiler reveals that the component renders in 1.3ms. That's a 40% improvement in efficiency.
Conclusion
According to the explanation offered by moment.js, using the library for date arithmetic operations yields code that is more readable. My small test reveals that the there is definitely an efficiency tradeoff. As always, it is up to the development team to decide which is more important. As for myself, I am definitely leaning towards the reduced time benefits.
Happy coding!
Top comments (3)
Tip:
date-fns
allows manipulation of native Date object with easy to understand utility functions.github.com/you-dont-need/You-Dont-...
Thank you! That's a really useful post. I've only used moment.js a few times and it's good to get new perspectives.