20230601 [usehooks-ts]

Daisy🌷·2023년 6월 1일

usehooks-ts는 바로 사용할 수 있는 타입스크립트로 작성된 React hooks 라이브러리다!

많은 hook들이 있었지만 그중에서 useLocalStorage()를 사용해 보았다.

useLocalStorage()를 사용하면?

로컬 저장소로 상태를 유지하여 페이지 새로 고침 후에도 유지되도록 해준다. dark theme에 유용할 수 있다. 이 훅은 첫 번째 매개변수에 저장소 키를 전달해야 한다는 점을 제외하면 useState와 동일한 방식으로 사용된다. 창 객체가 존재하지 않는 경우(SSR에서처럼) useLocalStorage()는 기본값을 반환한다.

예제 코드

import { useLocalStorage } from 'usehooks-ts'

// Usage
export default function Component() {
  const [isDarkTheme, setDarkTheme] = useLocalStorage('darkTheme', true)

  const toggleTheme = () => {
    setDarkTheme((prevValue: boolean) => !prevValue)
  }

  return (
    <button onClick={toggleTheme}>
      {`The current theme is ${isDarkTheme ? `dark` : `light`}`}
    </button>
  )
}
profile
티스토리로 블로그를 이전했습니다. 😂 구경 오세요! 👉🏻 https://u-ryu-logs.tistory.com

0개의 댓글