Problem with script to change number of Flatlist columns depending on rotation/size

I’m working on some code to calculate numColumns for a flatlist- intention is 3 on landscape tablet, 2 on portrait tablet, and 1 on portrait phone.

Here’s my code:

const [width, setWidth] = useState(Dimensions.get('window').width);
const [imageWidth, setImageWidth] = useState(100);
const [imageHeight, setImageHeight] = useState(100);

const [columns, setColumns] = useState(3);

useEffect(() => {
    function handleChange() {
        setWidth(Dimensions.get('window').width);
    }
    Dimensions.addEventListener("change", handleChange);
    return () => Dimensions.removeEventListener("change", handleChange);
}, [width]);

useEffect(() => {
    if (width > 1100) {
        setColumns(3);
    } else if (width <= 1099 && width > 600) {
        setColumns(2);
    } else {
        setColumns(1);
    }
    setImageWidth((width - (64 * columns) + 15) / columns);
    setImageHeight(((width - (64 * columns) + 15) / columns) * .6);
}, [width]);

imageWidth and imageHeight are passed to the render component of the flatlist to size an image.

It seems to work fine when I load it in landscape mode, but if I rotate to portrait, I get this:

enter image description here

Then, if I go back to landscape, it stays as 2 columns?

enter image description here

Any idea how I can fix this?

Source: React natvie