State’s value remains the same as initialized value in Flatpickr handler


This Content is from Stack Overflow. Question asked by florinpavel

I am trying to debug a very weird solution that I encountered on my project, but I can’t seem to reproduce the same issue whilst inputting the same code in Sandbox.

So, I am using react-flatpickr to create a calendar component. In the App, I use it like this.

const DatePickerCompo = () => {
  const [ value, setValue ] = useState(new Date());

  function clearDate() {

  return (
          value={ value }
          onChange={ setValue } />
      <Button type="primary" onClick={ removeDate }>Clear</Button>

The component itself is big, but I stripped down to the bare minimum, in order to understand what’s the issue.

export const DatePicker = forwardRef(({
  onChange = () => { }
}, forwardedRef) => {
  const [currentDates, setCurrentDates] = useState(value);

  const ref = useRef();

  function handleChange(dates) {

  useEffect(() => {
  }, [ value ]);

  return (
      ref={ ref }
      onChange={handleChange} />

Here’s the problem. In the handleChange function, currentDates has always the same value as the one we use to initialize the state. I do not understand what I am doing wrong, because, even if I initialize currentDates with null or any other value, it will remain the same everytime I change the date.

One thing to note is that, if I use a useRef to store the value, it works fine.


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?