Easy start using useState, useCallback and useEffect React Hooks

In this post, I’d like to show you an easy way to start using React Hooks. All puns to Hook with Robin Williams are intended.

I’m keen on using new things and luckily, I work with people who share this approach. Nevertheless, when I first read about React Hooks, I was lost like an old Peter Pan in Neverland. I was looking for Tinkerbell to help me out…

Luckily for me, a perfect occasion showed up sooner than I anticipated. We decided to upgrade our project to the latest React, and one of the High-Order Components (HOC) stopped working. I’ll show you the steps I took to refactor the old and ugly to something new and shiny.

The Pirates way (old component)

The component under review is a HOC responsible for debouncing onChange and onBlur events.

Let’s see the Pirates way of doing things:

import React from 'react'
	import debounce from 'lodash/debounce'
	import { isNil } from 'lodash'

	export const withDebounce = (Component) => {
	  return class WithDebounce extends React.Component {
	    constructor (props) {
	      super(props)

	      this.state = {
	        value: undefined
	      }
	    }

	    handleDebounceChange = (value) => {
	      this.props.onChange(value)
	    }

	    debouncedOnChange = debounce(this.handleDebounceChange, 100)

	    static getDerivedStateFromProps (nextProps, currentState) {
	      if (nextProps.value && (nextProps.value !== currentState.value)) {
	        return {
	          value: nextProps.value
	        }
	      }
	      return null
	    }

	    onChange = (value) => {
	      this.setState(() => ({ value }), () => this.debouncedOnChange(this.state.value))
	    }

	    onBlur = (event) => {
	      if (this.debouncedOnChange.flush !== undefined) {
	        this.debouncedOnChange.flush()
	      }
	      if (this.props.onBlur) {
	        this.props.onBlur(event)
	      }
	    }

	    render () {
	      const value = isNil(this.state.value) ? '' : this.state.value
	      return (
	        <Component {...this.props} value={value} onChange={this.onChange} onBlur={this.onBlur} />
	      )
	    }
	  }
	}

Argh! Pirates used getDerivedStateFromPropswhich in official React documentation is said to be reserved for rare cases.

#front-end-development #react #software-development #frontend #javascript #hook

Easy way to start using React Hooks
6.60 GEEK