skip to Main Content

I have a web application built on react js/next js where I have a couple of pages, including some globally used components, such as: Header and Footer.

The problem is, I don’t want to re-render the whole component and APIs used in global components. I am not sure. How can I do that?

Please help.

HOC: Main.js

export default function Main(props) {
  const { authentication } = useSelector((state) => state);
  const router = useRouter();
  const shouldRedirect =
    !!unsecureRoutes.find((i) => i === router.route) &&
    authentication?.loggedIn;

  return (
    <main id="main" className={classNames(props.class)}>
        <>
          <Header menuVisible={false} menuType={"Main Menu"} />
          <>{props.children}</>
          <Footer />
        </>
      )}
    </main>
  );
}

Home.js

export function Home() {
  const { user, loggedIn, authenticating } = useSelector(
    (state) => state.authentication
  );

  useEffect(() => {
    if (loggedIn && user) {
    }
  }, [loggedIn, user]);

  return (
    <Main>
        [Content goes here]
    </Main>
  );
}

export default Home;

2

Answers


  1. In React, component re-renders because of state change, props change or re-rendering of parent component and in most of the time, it should be fine. You can use the React Devtool Profiler to detect the exact cause then fix it when needed.

    However, in your case, I assume you are using useEffect and it keeps requesting for API when your component re-render. So the issue should be because of your useEffect.

    In that case you should check the second parameter of your useEffect, the dependencies array and make sure that each value of the array has the same value between render.

    You can add this to your component to log to the console and check which value triggers the useEffect:

    useEffect(() => console.log('value:', value), [value])
    

    Mind if the value are not primitive value, e.g object, array or function. In that case you have to memorize them using useMemo() hook before passing it to the dependencies.

    I need to look into your code to give you better solution. Good luck!

    Login or Signup to reply.
  2. You can use memo or useMemo Hook for stop the unnecessary re-renders of any components, just do it:

    import { memo } from "react"
    
    function Header() {
    return /* your code */
    }
    
    export default memo(Header)
    
    

    You can put console.log in the components and it will render only first time unless you use useEffect

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