Skip to content

Instantly share code, notes, and snippets.

@nabettu
Created January 4, 2021 08:01
Show Gist options
  • Save nabettu/a22f0166261957e9f3959c4966c30ff3 to your computer and use it in GitHub Desktop.
Save nabettu/a22f0166261957e9f3959c4966c30ff3 to your computer and use it in GitHub Desktop.
import React, { useState, createContext, useContext, useEffect } from "react";
import { Dimensions } from "react-native";
type ScreenSizeContextType = {
windowWidth: number;
windowHeight: number;
};
export const ScreenSizeContext = createContext<ScreenSizeContextType>({
windowWidth: Dimensions.get("window").width,
windowHeight: Dimensions.get("window").height
});
export const ScreenSizeProvider = ({ children }) => {
const [windowWidth, setWindowWidth] = useState<number>(
Dimensions.get("window").width
);
const [windowHeight, setWindowHeight] = useState<number>(
Dimensions.get("window").height
);
const handleChangeWindowSize = (e) => {
const { width, height } = e.window
setWindowWidth(width);
setWindowHeight(height);
};
useEffect(() => {
Dimensions.addEventListener("change", handleChangeWindowSize);
return Dimensions.removeEventListener("change", handleChangeWindowSize);
}, []);
return (
<ScreenSizeContext.Provider value={{ windowWidth, windowHeight }} >
{children}
</ScreenSizeContext.Provider>
);
};
export const useScreenSize = () => useContext(ScreenSizeContext);
export default ScreenSizeProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment