Get viewport/window height in ReactJS
Here's the speed-run version for obtaining viewport height in React by using window.innerHeight
inside a custom hook for real-time updates:
This code will create a hook, named useViewportHeight
, that keeps an eye on the viewport height—even when resizing!
How to dodge the SSR bullet
Server-side rendering in React doesn't provide window
—you're in command-line territory. Thus, to prevent a catastrophic failure, always verify window
's existence:
Class Component lifecycle: It's a circle of life
In the realm of Class Components, handling window height has its lifecycle:
Binding updateDimensions
in the constructor or using arrow functions guarantees the correct reference of this
.
Making it snappier, Reusability and Best Practices
Custom Hooks: Your magic spell
Custom hooks like useViewportHeight
offer convenient quick fixes and less clutter, making more readable components. Plus, you get to share logic all around town without cramming everything into higher-order components or render props.
Prevent Memory Leaks: Fight the good fight
In useEffect
, cleaning up after yourself is top-tier etiquette. Unwanted event listeners could lead to performance issues and memory leaks. So, before stepping out, make sure you've got everything (listeners removed).
Event Listener: Getting the name right
Always carefully jot down the correct event name (resize
) and a consistent event handler function before adding or removing listeners. Inconsistent references could leave you with unnecessary hang-ups (listeners).
Lifecycle Methods: Avoid the deprecated
When selecting React lifecycle methods, discard componentWillMount
; it's no longer invited to the party. Instead, invite componentDidMount
to initialize event listeners or state.
Stick the Landing with Responsive Design
Viewport height might play a vital role in styling or conditional rendering. React's proptypes and defaultProps offer default initial values and type assertions, making your components more predictable and less prone to errors.
Was this article helpful?