I have a function based component. I fetch data on redux toolkit with useAppSelector(). I wrote a console.log
within component to check what happens. When page refreshes again still console.log
appears again and again. My code is like this:
const blogs = useAppSelector(
(state: RootState) => state.introBlogsSlice.data.results
);
const dispatch = useAppDispatch();
useEffect(() => {
dispatch(fetchSomeBlogs());
}, []);
console.log("blogs", blogs);
I wrote it with useMemo()
like this.
const blogs = useAppSelector(
(state: RootState) => state.introBlogsSlice.data.results
);
const data = useMemo(() => {
return blogs;
}, [blogs]);
const dispatch = useAppDispatch();
useEffect(() => {
dispatch(fetchSomeBlogs());
}, []);
console.log("blogs", blogs);
But still it does not work it renders any time when page refreshes, regardless of what I do.
To summarise, How can I write this with useMemo()
to block extra renders?
2
Answers
If by page refresh you mean the literal browser refresh button, then everything is working as expected. The only data that survives a browser refresh lives in local/session storage, cookies, or indexed DB. Everything else needs to be re-queried.
The memo as it is written has no effect.
blogs
looks like it is already stateful & memoized byuseSelector
. But if it isn’t, then the reference to blogs will change every render causing theuseMemo
to recalculate every render as well.This code has no effect. It’s just a long version of writing
const data = blogs
. It will not have any effect on the rest of the execution of your component.useAppSelector
already has built in logic to skip rendering if possible. The important thing is what your selector code ((state: RootState) => state.introBlogsSlice.data.results
) returns. If that keeps returning the same value, then redux has no reason to render your component. But if the selected value does change, then your component will (and must) rerender.So if you are seeing additional renders that you think are related to the
blogs
variable, focus on making sure the selector returns a consistent value. I do not see any way to useuseMemo
to reduce the number of times your component renders.This is expected. When the page loads (including a refresh), the entire component tree must do its initial render.