So I am fetching data from my backend on a landing page in my app. This data is used in different parts, so I use redux for global state. The code is something like this:
//Landing Component
export default function Landing() {
const data = useSelector(state => state.data);
useEffect(() => {
if (!data.isAvailable) {
fetchData();
}
...
}, [])
...
}
//Some Component
export default function SomeComponent() {
const data = useSelector(state => state.data)
...
}
//Another Component
export default function AnotherComponent() {
const data = useSelector(state => state.data)
...
}
However as we know, if the user refreshes the page, the data stored in redux is re-initialized. The problem is, if the user refreshes while on the other pages, data does not get refetched. So what I do is I repeat the same useEffect in every other component that needs the data in order to refetch it in the event the user reloads in a different page.
//Some Component
export default function SomeComponent() {
const data = useSelector(state => state.data)
useEffect(() => {
if (!data.isAvailable) {
fetchData();
}
...
}, [])
...
}
I'm sure there are better ways to do this. I've heard of persisting data through localStorage or using redux-persist. But this data can become quite large so I don't think localStorage will do. Something like a global useEffect that will rerun whatever page the user may be. Thank you!