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:
Below, we define a function responsible for setting the state to the window’s current inner width and height:
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:
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