skip to Main Content

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


  1. 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 by useSelector. But if it isn’t, then the reference to blogs will change every render causing the useMemo to recalculate every render as well.

    Login or Signup to reply.
  2. const data = useMemo(() => {
      return blogs;
    }, [blogs]);
    

    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 use useMemo to reduce the number of times your component renders.

    it renders any time when page refresh

    This is expected. When the page loads (including a refresh), the entire component tree must do its initial render.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search