Den Dribbles

React Hook Basics

April 15, 2019

Hooks introduces State and Lifecycle Methods to function-based components.

Hooks make it really easy to share logic between components.

Some Basic Hooks

NameFunction
useStateComponent-level state
useEffectUse ‘lifecycle methods’
useContextAllow use of context system
useRefAllow func component to use ref system
useReducerAllow func component to store data through a ‘reducer’

Before Hooks

// components/App.js
import React from 'react';

export default App extends React.Component {
    state = {
        counter: 0
    }

    handleClick = () => this.setState({counter: this.state.counter++})

    render() {
        return <div>
            <button onClick={this.handleClick}>{this.state.counter}</button>
        </div>
    }
}

After Hooks

// components/App.js
import React, { useState, useEffect } from "react"

const App = () => {
  const [counter, setCounter] = useState(0)

  const updateCounter = () => setCounter(counter++)

  useEffect(() => {
    console.log("Counter updated!")
  }, [counter])

  return (
    <div>
      <button onClick={updateCounter}>{counter}</button>
    </div>
  )
}

Lifecycles with useEffect

useEffect allows us to effectively use a combined version of componentDidMount and componentDidUpdate.

Notes:

  • useEffect argument function cannot be an async func.
import React, { useEffect } from "react"

// second argument controls whether or not the arrow function is called
useEffect(() => {
  console.log("Counter updated!")
}, [counter])

Code Reuse Example

Believe it or not, what we can actually do is abstract the useEffect outside of the function component.

This is incredibly useful to create reuseable effects.


Related Articles

A personal blog on all things of interest. Written by Dennis O'Keeffe, Follow me on Twitter