Answer the question
In order to leave comments, you need to log in
Functional component doesn't re-render, what's the problem?
import React, {useState} from 'react'
import moment from 'moment'
function Component() {
const [date, setDate] = useState(moment())
return (
<div>
{date.month()}
<button onClick={() => setDate(date.add(1, 'month'))}>+1</button>
</div>
)
}
export default Component
Answer the question
In order to leave comments, you need to log in
Artur Galyaev , your date value does not change, because the moment object is mutable and when manipulating the date does not change the reference to the original object, date.add(1, 'month') is the same moment object. If you need to store exactly the entire moment object in the state, either add .clone() at the end to clone the moment object:
date.add(1, 'month').clone()
or instead of moment, use an immutable library for working with dates, for example, dayjs
I, in principle, do not recommend using moment when there is more lightweight counterparts (moment - 70.4
kB, dayjs - 2.8kB)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question