How can I get the recently updated value of the dimensions object in the Navbar.js component in the Home.js component. I tried to pass a callback function as props to Navbar.js from Home.js (as Home.js is parent of Navbar.js) but I cannot store the newly updated value of dimensions state in Navbar.js. Also if I pass the dimensions state as a dependency in useEffect it leads to infinite loop. Please help me.
**Home.js component**
const Home = () => {
const [heightNav, setHeightNav] = useState(0);
useEffect(() => {
console.log(heightNav);
}, [heightNav]);
return (
<div>
<Navbar
setHeight={(h) => {
setHeightNav(() => h);
}}
/>
</div>
);
};
**Navbar.js component**
const Navbar = ({ setHeight }) => {
const refContainer = useRef();
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
useEffect(() => {
if (refContainer.current) {
setDimensions(() => {
return {
width: refContainer.current.offsetWidth,
height: refContainer.current.offsetHeight,
};
});
setHeight(dimensions.height);
}
}, []);
return (
<Container ref={refContainer}>
</Container>
);
};
2
Answers
Hey try this for Navbar:-
You are missing dependencies in the useEffect of the navbar component. I have added setHeight to the dependency which will mount the component every time it is updated and render the updated values. This modified code might solve your problems!