Firebase with React, v2 Firebase with React, v2

Refactoring with React Context

Check out a free preview of the full Firebase with React, v2 course:
The "Refactoring with React Context" Lesson is part of the full, Firebase with React, v2 course featured in this preview video. Here's what you'd learn in this lesson:

Steve deletes unnecessary code that was rendered obsolete by the consumer.

Get Unlimited Access Now

Transcript from the "Refactoring with React Context" Lesson

[00:00:00]
>> Speaker 1: We can see the posts. Now we get to delete some code. So I don't need to pass posts into the post component anymore, which also means that in the application component, I don't need,
>> Speaker 1: To subscribe to that anymore. Which means I don't need to keep an application state, which means I don't need to unsubscribe anymore.

[00:00:29] We do need to actually unsubscribe from the auth still. Right, so I can delete all of that post logic.
>> Speaker 1: From the application component. Now, any component that needs to post, can get wrapped in that post context consumer, right, which will pass the posts in. But we can do one better.

[00:00:57] You can see that even I tripped up on that syntax a little bit with the extra curly braces because this is what we call the render prop pattern which is the child prop is a function that we pass stuff in to. Right, and I had a bug there because I had an extra set of curly braces, stuff along those lines.

[00:01:15] In the kind of newest version of React, we can actually hook into the context API and make this even cleaner. So I can actually say,
>> Speaker 1: const posts useContext, pull that in from React.
>> Speaker 1: And now I can take away this.
>> Speaker 1: And that bug I just created I can get rid of.

[00:02:05]
>> Speaker 1: So this will actually hook into the context API. It will grab me those posts, and I can just use them right here. And now I can take this post component. I can put it anywhere in my application. It's hooked up into the Firebase state. Hooked, literally, that was not a pun.

[00:02:23] This is a react hook. Let's make sure it works, too. Cool, I can take this post component cuz if you see in the application, this is it. It doesn't need to get anything passed in from the outside world. I can just place this if I need to move this to a sidebar, I can move it to a sidebar and do whatever I want with it.

[00:02:42] It is hooked into the application state using react hooks and that context API hooked up to Firebase. As stuff changes in Firebase, those are passed into the component. Right, I no longer have to do this thing where I'm passing everything down and around. So Firebase kind of exists in my React app and it's there for us.