Lifecycle - rkaku/react-hooks-101 GitHub Wiki

非同期処理にredux-thunkやredux-sagaは必要無い

useEffect

const [time, setTime] = useState(Date)

useEffect(() => {
  let hendle = setInterval(() => {
    setTime(Data)
  }, 1000)

  return () => {
    clearInterval(handle)
  }
})
const [xy, setXY] = useState(initXY)

function mousemoveHandle(event) {
  setXY({
    x: event.clientX,
    y: event.clientY
  })
}

useEffect(() => {
  window.addEventLister("mousemove", mousemoveHandle)
  return () => {
    window.removeEventLister("mousemove", mousemoveHandle)
  }
})

Async Await

const initProfile = {
  followers: null,
  publicRepos: null
}


const [profile, getProfile] = useState(initProfile)

async function getProfile() {
  const response = await fetch('url')
  const json = await response.json()

  setProfile({
    followers: json.followers,
    publicRepos: json.public_repos
  })
}

usePrevious

function usePrevious(value) {
  const ref = useRef(null)

  useEffect(() => {
    ref.current = value
  })
}

useLayoutEffect

function useDim(el, val) {
  const [height, setHeight] = useState(0)
  const [width, setWidth] = useState(0)

  useLayoutEffect(() => {
    let boundingBox = el.current.getBoundingClientRect()
    setHeight(boundingBox.height)
    setwidth(boundingBox.width)
  }, [val])

  return [height, width]
}
const [val, setVal] = useState(2)
const valEl = useRef(null)

const [height, width] = useDim(valEl, val)
<h1>Height: { height }, Width: { width }</h1>
<div ref={ valEl }>{ val }</div>
<button onClick={ () => setVal(val * 10) }>x10</button>

useCustomFetch

const [url, setUrl] = useState(null)
const [loading, error, data] = useCustomFetch(url)

function getFolowers(event) {
  if (event.key === 'Enter') {
    setUrl('https://api.github.com/users/' + event.target.value)
  }
}
function useCustomFetch(url) {
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [data, setData] = useState(null)

  async function customFetch(url) {
    try {
      let response = await fetch(url)
      let json = await response.json()
      setData({ json })
      setLoading(false)
    }
    catch(error) {
      setError(error)
      setLoading(false)
    }
  }

  useEffect(() => {
    setLoading(true)
    setTimeout(() => {
      if (url) {
        customFetch(url)
      }
    }, 3000)
  }, [url])

  return [loading, error, data]
}
{ loading && url && <div>Loading...</div> }

{ error && <div>Error: { error }</div> }

{ !loading && data && data.json && data.json.getFollowers && (
  <div>followers: { data.json.followers }</div>
)}
⚠️ **GitHub.com Fallback** ⚠️