React Hooks

Last updated: 2021-01-26

Some helpful hooks!

useToggle

import React, { FunctionComponent } from 'react'

import { useToggle } from '../hooks'

const ButtonToggleExample: FunctionComponent = () => {
  const [isOn, toggleIsOn] = useToggle()
  return <button onClick={toggleIsOn}>Turn {isOn ? 'Off' : 'On'}</button>
}

export default ButtonToggleExample
// Hook
import { useReducer } from 'react'

function useToggle(initialValue: boolean = false) {
  // Returns the tuple [state, dispatch]
  // Normally with useReducer you pass a value to dispatch to indicate
  // what action to take on the state, but in this case there's only
  // one action.
  return useReducer(state => !state, initialValue)
}

export default useToggle

References