I have been reading about this two hooks and try to find a workaround for my case now here but I cannot make it to work.
Basically, what I want to do is to render a certain amount of images if I am in desktop but less if I am in mobile (in this last case, I need a button to show the rest of the images)
So what did I do? started simply:
{images.slice(0, open ? images.length : 6).map(item => {
return (
<div}>
<Image
src={whatever}
alt={whatever}
/>
</div>
);
})}
In this way, I can show every image or only 6 if mobile. Even the button, quite simple
<Button
onClick={() => {
setOpen(!open);
}}
>
{open ? (
<text>
close
</text>
) : (
<text>
open
</text>
)}
now, what would be my initial state? well, that should depend on whats the width of the screen, right? okey, so this is how I solved it:
const [size, setSize] = useState([0]);
useLayoutEffect(() => {
function updateSize() {
setSize([window.innerWidth]);
}
window.addEventListener('resize', updateSize);
updateSize();
return () => window.removeEventListener('resize', updateSize);
}, []);
perfect, now I have 'size' who tells me the width of the screen at any moment the user changes the layout. So now its when I am getting stuck: There is no way to initialize 'open' to true or false depending on if size is > || < than a certain width. If I do like this:
const isMobile = size < breakpoints.tablet;
const [open, setOpen] = useState(isMobile);
here for example, if I load the page on desktop, 'isMobile' is false, but 'open' is still true.
or
const [open, setOpen] = useState(size < breakpoints.tablet);
but still, the value of 'isMobile' and 'open' are not sync. I guess because useLayoutEffect runs synchronously while useState async? In any case, how can I achieve having the 'open' variable having the correct initial state of 'isMobile'?