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
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:
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!
You can use
memo
oruseMemo Hook
for stop the unnecessary re-renders of any components, just do it:You can put console.log in the components and it will render only first time unless you use
useEffect