One of the things we love about programming is the ability to take code, place it in a function, and reuse it in other places in the software. Let’s imagine a scenario where we want to share our
localStorage code with other components so other components could synchronize state with
In the process, we’ll learn a few of the conventions for doing this and we’ll learn about some additional challenges that come with generalizing our code. As always, follow AHA programming practices!
A Community Resource means that it’s free to access for all. The instructor of this lesson requested it to be open to the public.
Question about the exercise left to the reader (remove old key from localStorage): It first seemed to me calling our custom hook from Greeting with a changing key doesn't make sense. But then yes Greeting could get that key 'name' from its props. Greeting could get its key prop being "firstName", then later on after some change in its parent that would need to greet the user by lastName instead, its key prop could become "lastName". Well ok, then Greeting must become linked to lastName in localStorage. But ... what is the sense to delete firstName from localStorage at that moment just because perhaps temporarily we greet by last name? And what if firstName in localStorage is used from another part of the app? That is why I don't understand.
An interesting exercise is to add a button (as in previous examples) and a counter which increments when you click the button, with state stored using the new useLocalStorageState hook. Does it work as expected? How can you fix it?