Skip to content

Instantly share code, notes, and snippets.

@antoniojps
Last active March 20, 2019 10:56
Show Gist options
  • Select an option

  • Save antoniojps/7b90d3288c4f05dd981f049bbb28f2c3 to your computer and use it in GitHub Desktop.

Select an option

Save antoniojps/7b90d3288c4f05dd981f049bbb28f2c3 to your computer and use it in GitHub Desktop.
Native react hooks summary

useState

// const [value, setValue] = useState(initialState)
const [isToggled, setToggle] = useState(false)

useRef

const Component = () => {
  const ref = useRef()
  return (
    <div ref={ref}>
      <button onClick={() => console.log(ref.current.className)}>
        Check Ref
      </button>
    </div>
  )
}

useContext

First create the context

import { createContext } from 'react'
export const UserContext = createContext()

Provide it a parent component

import { UserContext } from '...'
const Parent = () => {
  <UserContext.Provider
    value={{
      user: false
    }}
  >
    <Child />
  </UserContext>
}

Consume it on child component

import { useContext } from 'react'
const Child = () => {
  const userInfo = useContext(UserContext)
  ...
}

useReducer

import { useReducer } from 'react'

const initialState = {
  count: 0
}

function reducer(state, action) {
  switch (action.type) {
    case 'add':
      return {
        count: state.count + 1
      }
    case 'minus':
      return {
        count: state.count - 1
      }
    case 'reset':
      return {
        count: initialState.count
      }
    default:
      throw new Error()
  }
}

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, initialState)

  return (
    <div>
      <h3>{state.count}</h3>
      <button onClick={() => dispatch({ type: 'add' })}>+</button>
      <button onClick={() => dispatch({ type: 'minus' })}>-</button>
      <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
    </div>
  )
}

useMemo

Always use it on computed values so it doesnt run the function everytime the component re-renders

import { useMemo } from 'react'
const reverseWord = word => {
  console.log('function invoked')
  return word
    .split('')
    .reverse()
    .join('')
}
const title = 'Antonio Santos'
const TitleReversed = useMemo(() => reverseWord(title), [title])

useEffect

Not worth comparing to class life cycle, its a new paradigm, forget about lifecycle hooks when using functional components

A must read: A Complete Guide to useEffect by Dan Abramov

It’s only after I stopped looking at the useEffect Hook through the prism of the familiar class lifecycle methods that everything came together for me.

const [data, setData] = useState([])
const fetchData = async () => {
  // async request here
  setData(data)
}
// only re-fetch when the input changed
useEffect(() => {
    fetchData()
    // clean up function, runs on unmount
    // works with useLayoutEffect or useEffect
    return () => (document.body.style.overflow = originalValue)
  },
  // dependencies, will only run everytime this values update
  [input]
)

useLayoutEffect

When you need to mutate the DOM and/or DO need to perform measurements

Runs after react has performed all DOM mutations

useLayoutEffect(() => {
  setScrollHeight(document.body.scrollHeight)
})

Custom hook and useDebugValue

A custom hook is just a function that returns an array of [value, setValue] and takes an initial value

This example is a custom hook to update the document title

import { useState, useEffect, useDebugValue } from 'react'

function useTitleInput(initialValue = '') {
  const [value, setValue] = useState(initialValue)
  useEffect(() => {
    document.title = value
  })
  // display a label for custom hooks in React DevTools
  useDebugValue('Costum debug value here')
  return [value, setValue]
}

export { useTitleInput }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment