From the course: React Hooks

Unlock the full course today

Join today to access over 22,500 courses taught by industry experts or purchase this course individually.

Creating a custom Hook with context

Creating a custom Hook with context - React.js Tutorial

From the course: React Hooks

Start my 1-month free trial

Creating a custom Hook with context

- [Instructor] It's also possible to create a custom hook to make this even more reusable. So what I want to do here on line one is import useContext into the index.js file. So we're here in index.js, and we're importing useContext. The second thing is we still will want to create the context, but we don't need to export it 'cause we won't be using it in a different file. What we will want to export is a constant called useTrees. Now, this is our custom hook. That's going to return useContext with the TreesContext. So this is going to make all of this data accessible to the component, but when we use it in the component, we're not going to call useContext with TreesContexts 'cause that's a lot of typing. All we really want to do is we want to say import useTrees from ./, and then we're going to call useTrees. So now the output is the same. All of the data is the same. I can get rid of useContext here. useTrees is simply…

Contents