How awful is that :
useLayoutEffect(() => {
setWidth(ganttContainerRef.current.offsetWidth);
setHeight(ganttContainerRef.current.offsetHeight);
}, [])
useLayoutEffect(() => {
if (width > 0) {
setGanttReady(true);
}
}, [width])
useLayoutEffect(() => {
if (ganttReady) {
ganttRef.current.scrollTo({ left: 80 * 80 / 7 + 40 });
}
}, [ganttReady]);
i.e. rendering a component in 3 separate steps...
If I render 1 and 2 at the same time, the container width will be 0 (first render) because 2 is not displayed yet.
No matter what I do, if I do const top = refs.current[initiative.id].offsetTop;, offsetTop will have a value as if width was still 0. offsetTop is not updated with a rerender.
With the posted code above it works fine, but how awful is it? Is it doable to render a component in multiple phases or am I really hacking normal React behaviour?
With the posted code above it works fine, but how awful is it? Is it doable to render a component in multiple phases or am I really hacking normal React behaviour?
I wouldn't say it is awful, you could say it is not very efficient, but I would not worry about it if it isn't noticeable.
You can refactor it to something like this:
useLayoutEffect(() => {
let offsetWidth = ganttContainerRef.current.offsetWidth;
setWidth(offsetWidth);
setHeight(ganttContainerRef.current.offsetHeight);
if (offsetWidth > 0) {
setGanttReady(true);
ganttRef.current.scrollTo({ left: (80 * 80) / 7 + 40 });
}
}, []);
But the problem with this approach is as you can see it runs only on mount; which is Ok if that's what you want. So with your previous approach here:
useLayoutEffect(() => {
if (width > 0) {
setGanttReady(true);
}
}, [width])
you had the benefit that if width changed, then you could act on it, you don't get it with my version.
So it depends.