A
A
Artur Galyaev2020-06-23 19:09:14
React
Artur Galyaev, 2020-06-23 19:09:14

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

https://codesandbox.io/s/billowing-bash-jp5h8
The moment js library, I want to change the month when the button is pressed, but the component is not re
-rendered (it works with class components)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2020-06-23
@art5455

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 question

Ask a Question

731 491 924 answers to any question