I have a very simple functional component, that gets a date from the localStorage and displays it. I have two buttons to add or remove weeks from the date, and I expect the new date to be shown. However, the component doesn't get rendered.
import React, { useState } from "react";
import { monthList } from "../common/lists";
const Navbar = () => {
const [focusDate, setFocusDate] = useState(
Number(localStorage.getItem("focusDate"))
);
const [month] = useState(new Date(focusDate).getMonth());
const [year] = useState(new Date(focusDate).getFullYear());
const onLeftClick = () => {
setFocusDate(focusDate - 504000000); //one week
localStorage.setItem("focusDate", focusDate);
};
const onRightClick = () => {
setFocusDate(focusDate + 504000000);
localStorage.setItem("focusDate", focusDate);
};
return (
<div className="navbar-container">
<div className="calendar-navigation-container">
<div className="navbar-menu-item">
<i onClick={onLeftClick} className="fas fa-chevron-left"></i>
</div>
<div onClick={onRightClick} className="navbar-menu-item">
<i className="fas fa-chevron-right"></i>
</div>
<div className="calendar-year">{`${monthList[month]} ${year}`}</div>
</div>
</div>
);
};
The expected behavior for this component is that it gets the timestamp, then shows the month and the year of that timestamp. When loaded, it properly shows January 2021, however it doesn't render the component when I click several times on onLeftClick, though I was expecting it to show December 2021. The calculations are correct, I think I'm missing here the concept of functional component rendering. This would have been so much easier with Class components, but I want to learn functional ones as well. What am I missing here?