Create reusable custom hooks

InstructorKent C. Dodds

Share this video with your friends

Send Tweet

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 localStorage (or we could even do it with different variables in the same component). Take a step back from React specifically and considering how code reuse works in JavaScript in general, we can simply make a function, put our relevant code in that function, and then call it from the original location. That process works exactly the same with React hooks code, so let’s do that!

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!

Free Community Resource

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.

Fred
Fred
~ 10 months ago

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.

David
David
~ 8 months ago

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?