Create reusable custom hooks

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!

Fred
Fred
~ 5 years 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
~ 4 years 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?

~ 3 years ago

David, cool exercise you suggested. :) Here's my solution https://codesandbox.io/s/distracted-dubinsky-gcybl?file=/index.html

Jared Eddy
Jared Eddy
~ 3 years ago

How does this line of code work? const [name, setName] = useLocalStorageState('name')

I understand useLocalStorageState('name') will run and return the state and setState properties. I can infer that it assigns those values to your array ['name','nameState'] but how? Is that a React feature? I've never seen an array declared without a variable name.