Reusing logic with React Hooks

The keyboard event hook for React

One of the big React problems that hooks will solve is the ability to reuse logic. In the present, using component classes it can become very difficult to reuse logics that are bound to the component lifecycle. Now with hooks, it’s very easy to do.

Let’s look to an example. If we wanted to add an on “Escape” key pressed we would need to do it this way:

import React from 'react'
class Component extends React.Component {
  componentDidMount () {
window.addEventListener('keydown', this.handler)
}
  componentWillUnmount () {
window.removeEventListener('keydown', this.handler)
}
  handler (event) {
if (event.key === 'Escape') {
alert('Escaped')
}
}

render () {
return <span />
}
}

But now, with hooks, we can do it this way:

import React from 'react'
import {useEffect} from 'react'
function useKeyboardEvent(key, callback) {
useEffect(() => {
const handler = function(event) {
if (event.key === key) {
callback()
}
}
    window.addEventListener('keydown', handler)
return () => {
window.removeEventListener('keydown', handler)
}
}, [])
}
export default function Component(props) {
useKeyboardEvent('Escape', () => {
alert('Escaped')
})
return <span />
}

I don’t want to compare which one is simpler to write. The big win here is that we could now save that custom hook in a different file or package, import it and use it anywhere we want with just one line.

So, the code before becomes this:

import React from 'react'
import useKeyboardEvent from './useKeyboardEvent'
export default function Component(props) {
useKeyboardEvent('Escape', () => {
alert('Escaped')
})
return <span />
}

Which is significantly simpler and better in any way.