astoilkov / use-local-storage-state

React hook that persists data in localStorage
MIT License
1.09k stars 39 forks source link

[v14] How to use a value from another hook as a default value? #38

Closed discosultan closed 2 years ago

discosultan commented 2 years ago

For example, in v13 I had the following code:

export default function App() {
  const [darkMode, setDarkMode] = useLocalStorageState(
    "darkMode",
    useMediaQuery("(prefers-color-scheme: dark)"),
  );
  // ...
}

In v14, I needed to create the local storage hook first at the top level like this:

const useDarkMode = createLocalStorageHook("darkMode", {
  defaultValue: useMediaQuery("(prefers-color-scheme: dark)"), // <-- React Hook cannot be called at the top level.
});

export default function App() {
  const [darkMode, setDarkMode] = useDarkMode();
  // ...
}

What's the workaround? Could the API be changed to accept a default value through the generated hook instead?

const useDarkMode = createLocalStorageHook("darkMode");

export default function App() {
  const [darkMode, setDarkMode] = useDarkMode(useMediaQuery("(prefers-color-scheme: dark)")); // <-- Not sure if this makes sense but would be similar to the `React.useState` hook.
  // ...
}
astoilkov commented 2 years ago

I think you are right. I've probably made a mistake with this API. Give me a little while to think. I will experiment with reverting back to using a useLocalStorageState hook.

astoilkov commented 2 years ago

Done. I've released v15 which reverts to useLocalStorageState hook.

I should admit the new design is better (also with a smaller bundle size). I should also admit that I feel a little dump. I though a lot about the change but failed to recognize that the answer to the original question I had changed with the new implementation. Somedays you think you are a great developer and somedays 💩. Thanks to @ha-ku and @discosultan to make me see this error.

Sorry for the inconvenience. I hope you like the new design. Please let me know if everything works for you.

discosultan commented 2 years ago

Thanks for the quick fix @astoilkov! Can confirm that v15 solves the problem for me :)

Cheers!

ha-ku commented 2 years ago

Thanks! I'm already using v15 in my project. It works fine for me now!