Image for post

Let’s start by defining the piece of state we ultimately want the hook’s consumers to receive. We define it with a shape of { x: number; y: number } and set the default values to the window’s current (at the time the hook was first called) inner width and height, respectively:

Defining the state to be kept by the hook

Below, we define a function responsible for setting the state to the window’s current inner width and height:

Image for post

Now let’s create an effect responsible for subscribing to the resize event so we can run our arbitrary function whenever the DOM dispatches it:

Effect using native js listeners

In the cleanup of the effect, we remove the listener by passing thesame reference to the function we subscribed with in the first place. Finally, we return dimensions.

#javascript #react-hook #programming #reactjs #react

Subscribe to the Window’s Dimensions With React Hooks
1.50 GEEK