Blog Development Frontend Open Source React react-hooks Technology

Say Hello to React Browser Hooks

react-hooks

react-hooks

‘React Browser Hooks’ is an Open Supply library containing a number of customized hooks that combine with widespread browser performance.

The Drawback & Our Motivation

Typically browser occasions and features are instantly added to elements, which may:

  • Add considerably to a element’s footprint
  • Dilute the core performance and purity of the element resulting in much less readable code
  • Create disjointed code the place associated logic finally ends up aside, resulting in much less maintainable code
  • Require using lifecycle occasions or state to handle, which means a React class element have to be used as an alternative of a stateless useful element
  • Take some investigation for a developer to determine (particularly if there are nuances), leading to misplaced time / inaccurate estimations of duties
  • Be non-standard between browsers, which means builders need to analysis cross-browser help and register a number of occasions / name a number of features e.g. WebKit, Microsoft, opera and Mozilla variations of occasions.
  • Result in reminiscence leaks if the lifecycle isn’t managed appropriately
  • Typically require throttling (for rapid-fire occasions like scrolling or mouse place to minimise the impression on efficiency)
  • Result in re-inventing the wheel

We did some rudimentary analysis on widespread browser occasions and, from a primary search, discovered that there are over 150,000 modules on GitHub that add occasion listeners instantly, tens of hundreds of that are particular browser occasions together with ‘mousemove’, ‘fullscreen’, ‘resize’ and lots of others.  These are sometimes registered in element lifecycle occasion ‘componentDidMount’ and deregistered or eliminated within the ‘componentWillUnmount’ occasion. Our preliminary analysis revealed that as much as 25% of registered occasions will not be deregistered. It additionally highlighted that the identical browser integration code is being repeated time and again, and so it’s an actual case of builders re-inventing the wheel.

Internally inside our tasks, we’ve typically carried out listeners immediately inside elements, and so we felt a library of hooks can be helpful to standardise and simplify the re-use of a lot of these browser occasions.

Why Hooks?

React Hooks are a brand new addition to React.js, that makes it a lot simpler to create and use libraries of software logic which are made up of full vertical slices of a element. Earlier strategies for separating software/presentation logic typically result in ‘nesting hell’, and sometimes builders didn’t hassle creating/importing libraries for quite simple features in consequence.

Take a look at Dan Abramov’s article on what ought to and shouldn’t be a hook. 

Instance Earlier than Hooks

Think about you needed to create a button element, for a video participant, that when clicked opened the browser in fullscreen mode.  You may implement one thing like the subsequent instance.

import React from ‘react’

class FullScreenButton extends React.Element
constructor(props)
  tremendous(props)
  this.state =
    fullscreen: false
  

handleFullscreenChange = (e) =>
  let fullscreen = false
  if (doc.fullscreenElement ||
    doc.mozFullScreenElement||
    doc.webkitFullscreenElement ||
    doc.msFullscreenElement ||
    doc.fullscreen ||
    doc.mozFullScreen ||
    doc.webkitIsFullScreene ||
    doc.fullScreenMode )
    fullscreen = true
  
  this.setState (fullscreen)

handleToggle = (e) =>
  const el = doc.documentElement
  if(!this.state.fullscreen)
    if (el.requestFullscreen)
      el.requestFullscreen()
     else if (el.mozRequestFullScreen)
      el.mozRequestFullScreen()
     else if (el.webkitRequestFullscreen)
      el.webkitRequestFullscreen()
     else if (el.msRequestFullscreen)
      el.msRequestFullscreen()
    
   else
    if (doc.exitFullscreen)
      doc.exitFullscreen()
     else if (doc.mozCancelFullScreen)
      doc.mozCancelFullScreen()
     else if (doc.webkitExitFullscreen)
      doc.webkitExitFullscreen()
     else if (doc.msExitFullscreen)
      doc.msExitFullscreen()
    
  

componentDidMount()
  doc.addEventListener(‘webkitfullscreenchange’, this.handleFullscreenChange, false)
  doc.addEventListener(‘mozfullscreenchange’, this.handleFullscreenChange, false)
  doc.addEventListener(‘msfullscreenchange’, this.handleFullscreenChange, false)
  doc.addEventListener(‘MSFullscreenChange’, this.handleFullscreenChange, false) //IE11
  doc.addEventListener(‘fullscreenchange’, this.handleFullscreenChange, false)

render()
  return
    
  )

componentWillUnmount()
  doc.removeEventListener(‘webkitfullscreenchange’, this.handleFullscreenChange)
  doc.removeEventListener(‘mozfullscreenchange’, this.handleFullscreenChange)
  doc.removeEventListener(‘msfullscreenchange’, this.handleFullscreenChange)
  doc.removeEventListener(‘MSFullscreenChange’, this.handleFullscreenChange)
  doc.removeEventListener(‘fullscreenchange’, this.handleFullscreenChange)

export default FullScreenButton

As you possibly can see from above, there may be a number of occasions for a number of browsers and code mucking up a element that might be a lot purer. All of this results in the element earlier than any additional logic is added.

Contemplate the identical element utilizing a customized fullscreen hook from a library like react-browser-hooks:

import React from ‘react’

import useFullScreen from ‘@nearform/react-browser-hooks’
export default perform FullScreenButton ()
const toggle = useFullScreen()
return (
    
    
  )

On this instance, your complete vertical slice of full-screen performance has been stripped from the element.  All the logic that offers with activating full-screen mode and discovering fullscreen standing, is now in its personal tidy library that can be utilized by any future element that requires this performance.  On this case, a button element may even be pointless because the hook could possibly be used immediately inside the video participant element, whose important component could possibly be handed not directly to the hook and toggle might be fired from a doubleClick occasion.

There are different nuances with full-screen performance, that always builders might not contemplate till they should implement it (including unknown time to an estimated process),  e.g. is the appliance full display due to the browser menu full-screen choice or is it as a result of a component was made full-screen from inside an software. These are the sorts of issues a developer shouldn’t have to fret about fixing.  It’s one thing a library like react-browser-hooks ought to maintain.

All of those preliminary hooks have been developed with ardour, care and curiosity by builders who all the time attempt to write down good code.

The primary model of react-browser-hooks incorporates hooks for numerous widespread duties together with:

  • On-line/Offline hook: Decide if the browser has an Web connection.
  • Orientation hook: Determines the angle of orientation of the display
  • GeoLocation hook: Will get the consumer’s present location and retains it up to date as they transfer, very useful for mapping purposes.
  • Mouse Place hook: Will get the present mouse coordinates
  • Scroll hook: Will get the present browser scroll left and prime positions
  • Resize hook: Will get the width and peak of the web page
  • Full-Display hook: Determines if the display or a component is in full-screen mode, a second hook exist to verify if the browser is full display (e.g. F11 on menu)
  • Web page Visibility hook:  In the event you browse away or again to a tab, this hook will let your element know (perhaps hibernate some exercise or set the tab title to one thing to entice them again).
  • Media Controls hook: Supplies entry to media controls like play, pause, search and quantity for controlling audio/video parts.

We plan on including extra over time as demand dictates.  We additionally see this library as a useful base library for constructing some extra complicated libraries on prime and we invite others to make use of it for such functions.

Testing

Our objective is to have a particularly strong set of hooks that work seamlessly throughout as many browsers as attainable. When it comes to testing, as a part of our steady integration course of, we’ve got unit exams and protection evaluation in place.  We additionally use netlify to deploy our demo on each department submitted so reviewers can check out code that’s present process a pull request.

We recognize suggestions from the group ought to any errors be discovered on this early model of react-browser-hooks.

See our demo (which doubles as our documentation), for extra info on every of those customized hooks and to see them in motion.

To put in the package deal into your undertaking use ‘npm i @nearform/react-browser-hooks

Then import a hook and use it inside a useful element.  You’ll be able to actually combine them in seconds.

If you need to contribute to this venture or increase a problem/request, please go to our github venture web page

 

At NearForm, we’ve huge expertise in constructing options throughout a broad tech stack to ship decreased complexities and overcome widespread hurdles. In case you are creating trendy purposes and leveraging net applied sciences, contact us to study extra about how we may also help.

You may also like a few of our earlier weblog posts on React:

Overlook every thing you discovered about React – Hooks rocks! 

Managing React state with Render Props

Exploring React Portals

Sharing React elements with Lerna

 

📸 Credit score: PixaBay

About the author

Admin