Skip to main content

useWindowSize

An example of a Reactive component that gets the browser's window size.

If the size of the browser changes, the width and height state values change.

0 x 0

Reactive Adapter

import { reactive } from "@cfcs/core";

const REACTIVE_ADAPTER = ({ onInit, onDestroy }) => {
const obj = reactive({ width: 0, height: 0 });
const callback = () => {
obj.width = window.innerWidth;
obj.height = window.innerHeight;
};
onInit(() => {
window.addEventListener("resize", callback);
callback();
});

onDestroy(() => {
window.removeEventListener("resize", callback);
});

return obj;
};

Frameworks

You can create a Reactive Component by importing the @cfcs/react module and using the useReactive function.

import { useReactive } from "@cfcs/react";

function useWindowSize() {
return useReactive(REACTIVE_ADAPTER);
}
export function App() {
const {
width,
height,
onResize,
} = useWindowSize();

return <div>{width}x{height}</div>;
}