rehooks / local-storage

React hook which syncs localStorage[key] with the comp.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Update value and set potential initial value

EmilTholin opened this issue · comments

This is super cool! You are really fast!

What are your thoughts on extending the API with something like initValue that would be used if the key has no value in localStorage? And maybe it could be useful to return the updateLocalState function as well, so it can be updated in the component?

import useLocalStorage from "@rehooks/local-storage";

function MyComponent() {
  let [name, setName] = useLocalStorage("name", { initValue: "Emil Tholin" });

  return (
    <div>
      <h1 onClick={() => setName("Eric Johnson")}>{name}</h1>
    </div>
  );
}

I understand perfectly well if you think this is outside the scope of the hook, but just thought I'd ask!

Would you want to set the value in localStorage as well?

I'm not entirely sure what would be best, to be honest. Some way of setting an initial value that persists to localStorage if there is none, as well as a bool like e.g. clear to force the localStorage to be cleared might be nice?

I haven't thought about it that deeply. What do you think?

The point of hooks is not to wrap every API, but to connect React to your environment or to your state or whatever. I think you should just use localStorage.setItem

The idea by what I understood, was that data would flow from localStorage to the component. So to update the value you would use the localStorage.setItem(key) and the useLocalStorage hook would be used to subscribe to any change event there.

Yeah, that makes sense. That's a much better idea. Thank you both.