There is nothing specific to the React library that's made to help with storing data in the browser, you'll have to use browser APIs for that. Using a cookie is probably your best bet.
Assuming your date is stored in the Javascript Date
object, here's a start to what I would do:
// saves the date value as a string to a cookie called savedDate
function writeDateCookie(date) {
document.cookie = `savedDate=${date.toString()}; max-age=3600`;
}
// loads the date object from the savedDate cookie
// returns the date as a string or null if it does not exist
// can be converted back to date with new Date(dateString)
function getDateCookie() {
const cookieObj = Object.fromEntries(
document.cookie.split("; ").map(c => {
const [key, ...v] = c.split("=");
return [key, v.join("=")];
})
);
return cookieObj.savedDate || null;
}
EDIT
Since the addition of hooks, there is an easy way to react-ify my original answer. You can easily make a hook to get and set a date cookie using the above functions like so:
function useDateCookie () {
const [date, setDate] = useState(() => {
return getDateCookie();
});
const updateDate = (value) => {
setDate(value);
writeDateCookie(value);
};
return [date, updateDate];
}
And you can use it like this:
const App = () => {
const [date, setDate] = useDateCookie("")
return <div>My date is: {date.toString()}</div>
}
Alternatively, you could use a pre-built solution which handles all types of cookies using something like react-use-cookie
.