Resize event in react

share link

by vsasikalabe dot icon Updated: Feb 21, 2023

technology logo
technology logo

Solution Kit Solution Kit  

Responding to the available visual space, we attempt to create React apps with flexible UIs. Sometimes, this would be more practical. In such instances, When the window or viewport size changes, it can be useful to re-render a React component explicitly. When its props or state changes, React will re-render a component to trigger a re-render of MyComponent in the example, we'll set the internal state on the component if the event is detected. 

When the document view (window) has been resized, the resize event fires. Registering to resize event handlers on any HTML element at some earlier was possible. Getting the current size of the browser window is a prevalent need. An object returns with the window's width and height by this hook. The width and height value will be undefined if this is executed server-side (no window object). addEventListener accepts the event type. We will add the event listener to the useEffect hook to remove an event listener in React. Return a function from the useEffect hook. When the component unmounts, use the removeEventListener method to remove the event listener. 

This can be done with useEffect. The function also returns a function when passing a function to useEffect. The returned function will be called to perform any needed cleanup. To call and bind the new function that returns to the debouncedHandleResize variable, we must wrap handleResize in a debounce(). Then we use this variable both in the event listener setup and cleanup. 

Here is an example of how to create Resize event in Reactjs: