siddharthkp / react-ui

Customisable components and primitives based on design tokens
https://react-ui.dev/
418 stars 53 forks source link

feat: Persist theme in localStorage #94

Open iamdarshshah opened 4 years ago

iamdarshshah commented 4 years ago

[ Reference #91 ]

Custom Hook for the theme change that will update the theme globally by adding it to the localStorage.

This will help us to persist the selected theme in local storage and use it every time the page is refreshed.

Let me know your thoughts. Thanks

Here is the code for custom React hook:


const useThemeState = (defaultValue, key) => {
  const [value, setValue] = React.useState(() => {
    const theme = window.localStorage.getItem(key)

    return theme !== null ? JSON.parse(theme) : defaultValue
  })

  React.useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(value))
  }, [key, value])

  return [value, setValue]
}
vercel[bot] commented 4 years ago

This pull request is being automatically deployed with Vercel (learn more). To see the status of your deployment, click below or on the icon next to each commit.

🔍 Inspect: https://vercel.com/sid/react-ui/cmyz07wbv ✅ Preview: https://react-ui-git-fork-iamdarshshah-feat-theme.sid.now.sh

iamdarshshah commented 4 years ago

@siddharthkp & @rubenmoya Any updates or feedback on this?