Socket.io + ReactJS Tutorial | Learn Socket.io For Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys how's it going i'm back here with another video and today i decided to bring this tutorial where i'm going to be teaching you guys the basics of socket io while being used with react so a lot of you guys know that socket io is a library which allows you to send real-time bi-directional data which allows you to make a lot of cool projects for example a chat app which is the most common use case for it and it's a really really important library because learning about web sockets is really important in the programming world or in the web development world so for that reason i decided to bring this video i already have some videos using socket io however i don't have a video where i basically just explained the library and go over the basics of it especially in react so that's what i'm going to be doing in this video before we get into the video if you could leave a like and subscribe i would massively appreciate it would help push my videos to more people which would help support the channel so if you could do that i'll be very grateful so with that in mind let's get into the video [Music] [Applause] [Music] [Applause] [Music] [Applause] okay everyone so let's get started so in order to set up any project using socket io and react you need to first create the react part of your application and also keep up with a server part of your application so that you can write all the socket io code so to do that what i'm going to do is i just opened up a project like a folder inside of vs code as you can see and currently there's nothing in it but i'll right click on here and create two different folders the first one will be the client folder and the second one be the um server folder so i'll just say server over here and we'll have two folders inside of our project now the reason why we're dividing them like this is because um we need to have a front end and the back end the socket io um library exists inside of an http server so we need to create that server in order to use the library so what i'm going to do is i'm going to change my directory over here on my terminal towards the client folder so that we can create a react type inside of here and i'm going to run yarn create react tab now obviously if you're using npm just write npx create react tab but i'm using yarn so i'm using the yarn command and then i'm going to come over here open another terminal and go towards the server folder so i'm going to change my directory to server and i'm going to run yarn in it so your init will just create a simple package.json file inside of our servo and over here we just want to create a file called index.js so we can set up our actual express server so we're going to be using express and node to create our back-end but sakurai works with any other library for for back-ends right it doesn't matter if you're using javascript you can use other languages you can do this in java go c plus plus whatever you want sockareo has a version for each of those languages they're all the same like it doesn't matter because the front end and react will be the same um the only difference will be how you create your back-end so we're doing it with node.js and express i find it easy and simple to explain so we're going to be using this so now that we created our index.js we need to install some of the packages that we're going to be using in this tutorial for example in our back end over here i want to install first of all express so i'm gonna run yarn at express um just to create our server then we need to then we need to install course which is necessary because like i mentioned socket io works as a front like as a full stack project so you'll serve data to your front end um so in order to make that connection with your front end you do need to install course or else react won't allow you to make the connection work so we'll install the course library then i want to install the node 1 library which is something really useful for every node.js project it just allows you to restart the server every time you save or make any changes and then finally we're going to install the socket.io library so while this is installing because it installed really quickly we can come over here to our index.js which is the file over here and just start writing our code for our backend now what i'm going to be doing in this tutorial is at least in the first part of it i'll explain to you guys how to create a very simple um application really simple application um to demonstrate a very cool use case of the socket io library um i'll show you guys step by step and then i'm going to show you guys another example of a more complex application and go over it step by step so that you guys can get also an idea of how this is more well implemented into bigger projects so the first application we're going to be building is really simple it's just a website where there's a button and an input and two people open this website on different computers so when the one of the users write a message and clicks on the button the other user will receive that message on real time without having to um i don't know make any api requests or any like it will have a request but it will be like sent through web sockets so just so you guys can get an idea of what we're building so in order to do that we need to start out by creating our express server and to create an express server it's pretty simple um you just write a variable called express and set it equal to require express um if you're interested in knowing what library i'm using here where it all completes it's just a github copilot library i know a lot of people ask this all the time um but yeah that's that's basically it then we want to create our app variable this app variable is just an instance of the express library and it's going to be used to create our backend server so down here what i want to do is i actually want to create an instance of the http library so i'm going to say http equals to require http now if you're used to working with express you don't necessarily need to create your server this way but like i mentioned um socket io is is is created upon an http server so through their documentation you'll see that this is the recommended way of doing this it used to be different you could do it with other methods but nowadays i find that this is the the way to go so we'll just create an http server and then come down here and say const open up some curly braces set this equal to require and finally we'll require the socket.io library like this and what we're going to grab from this library is a class called server and this class will be used right over here we'll just say first of all create the actual http server by saying cons server equals to http.create server and we'll pass app right over here this is the it's how we create an http server with express by the way a lot of people like i mentioned use different methods but this is very simple as well it works the same way and then we'll have to create this variable called io which will be the variable we'll be using to do anything related to socket io in our backend so it's a very important variable we'll just set it equal to a new server we say new because like i mentioned server is a class so you need to instantiate a new instance of it so we say server and then over here we pass our http server and then we just open some curly braces and put some information related to course so a lot of people have a lot of issues with um socket io um and connecting to it so it's usually course related so what i find it to be good is you just set your cores over here and you can put all the different properties of it for example you can put the origin of where your front end will be and the front end for us will be react and for if you've used react before you might know that react runs at least in the local in your local computer on a url called localhost at the port 3000 so i'll change this to localhost because i misspelled it so this is the the link the url for our frontend and we can also specify other stuff like what kind of methods are we accepting so i can put something like a get request or a post request i'll just leave it like this because we're not doing anything complicated but this is basically a way to specify all the properties and functionalities that you want with course inside of your project so we just set up this variable and this will allow us to work with socket io which is amazing now we before we go into anything related to socket io i also need to set our project to accept course by applying the course middleware so i'm going to say app.use and i need to import the course library so i'll say const course equals to require course and i'll just pass it directly over here right inside of this thing and now it should be fine now if you're not familiar with course i would i wouldn't worry that much it is mostly like it doesn't affect your project that much in the sense that you won't be doing a lot with it um just applying the middleware is fine for many projects because it will prevent you from getting connection errors so i would just not worry that much about it and keep it simple now we have basically our server done we just have to set it to listen to a port so i'm going to say server dot listen like this put a port we're going to run on 3001 because our react app is running on 3000 then we're going to create a server over here which will console.log a message saying um server is running or something like this right so save this and we can test this out right i can run um node index.js to run the server because we're running a node server uh that starts in the file index.js and if i run if i press enter you'll see it says server is running now there's a thing i want to show you guys we did install the nodemon package and the way we use nodemon is basically we come to our package.json we add a scripts tag over here like this and then we add a start tag um not a serve a start tag like this and then we'll put nodemon nodemon index.js now what this will do a lot of people already know is now instead of running node index.js and having to kill the server and restart it again every time we make a change in our backend we'll just run yarn start and it will continuously run our server as you can see over here so now we got the server out of the way right the back end is almost completely done we haven't written anything with this i o variable over here however i want to move on to the front end before we do anything with this because it will give you guys a clear view of what we're doing so let's go to our front end which by now should have a bunch of files because we ran the yarn create react tab and let's also open the front end terminal which as you can see it finished running the command we'll run yarn start over here which as you can see is running our local host inside of our browser so what we want to do is i want to close this and um i'll just save this and then come to our source folder and delete um a couple files that come with the create react type command so i'm going to delete the setup tests the logo file the index.css and the app.test.js those files are necessary for our project so i just like to remove them to keep the project looking simple then i'm going to come to the index.js and delete the index.css import because we just deleted that file and also on the app.js i'll delete the logo and everything inside of here because we're going to start from scratch and as you can see it is working fine it's just an empty website so what i want to do is as i mentioned i want to have an input and i also want to have like a button so i'm going to add both of them over here by adding both an input tag and a button tag like this the button will say something like send a message and the input will have a placeholder saying message because it will be where you write your message so we can see over here that this is exactly what appears now i did zoom in like a lot as you can see so you guys can see better on the video but you can style this however you want it's not an actual project it's just a way for me to explain to you guys how socket io works so what exactly do i want to do here well the way socket io works is you create certain events and you name those events and basically you can either listen to an event or emit an event so when i say emit an event i basically am emitting some sort of i'm sending some sort of data to all the people who are listening to that specific event so everyone who's listened to an event will receive that data and they can do whatever they want with it including sending some data back so when you when you're sending messages to another user it's you basically create an event where you're able to send a message so you emit that message and then the other user will be listening to that message or listening to that event so that when something is received in that event they'll be able to receive the message now all those words might be confusing for now because we haven't written any of the socket io code but this is exactly what we're going to be doing now so we're going to create a function over here called send message right and this will be called whenever we click on the button so i'll pass an on click to this button over here so i'll say on click and i'll pass the send message i'll save this and then what i want to do is inside of this send message function i want to be able to emit some sort of message to some sort of people right but we don't have this access to this emit function over here because it doesn't make sense there's nothing in react that does that so here's where socket io comes in um there's also a socket arrow library for react so we installed one for the back end but we also need to install the the client version of this library inside of our react project so i'm opening up another terminal over here and i'm moving towards the the client folder again so change directory to client then all i want to do is i want to say yarn add socket dot io dash client like this i'm going to press enter and this is the library we use for using socket ao in react then now that we have this library installed we need to set up the connection to our socket io server that exists in our backend now to do this we're going to come over here at the top then we're going to say import io from the socket io library this is as you can see a function from the library then all we have to do is say const socket so we're creating a variable called socket and setting it equal to io.connect like this and then we pass the url for our backend server now similar to what we did with the with the index.js file over here we put the url for the front-end now we're putting the url for the back-end and the difference is just the number over here at the back because the back-end is running on the port 2001 and the front-end is running on the port 3000 now we'll save this and we finally have a connection to our socket server now what we do is we can use this to emit or listen to to events whenever we want to so when i said over here that i wanted to emit a message now i can technically do that i can come over here and say socket dot emit which is a function and i can emit some sort of event so that another person can listen to that event so what happens is um we need some like we can't send a message i made a message right over here and send it to another um user in the client so you can emit a message directly to another user in the client however what you can do is you can emit a message or an event that will be received in the back end of our application like over here and then when the pers when the backend receives that event they can then emit another event that is received in the front end so the back end is necessary as a layer to connect those events and that seems weird in the beginning but as i mentioned as you guys write the code and you guys see the project you'll start understanding and getting the hang of it so in order to emit a message when you send when you click on the button we need to come to our back end over here and start listening to some events now how exactly do we listen to some events well the first thing we do is we say io dot on which is the way we listen to events you basically put on and then you put the first event that we need to listen to whenever we have an socket io server that event is called the connection event which the minute you there's a user which is connecting to the server so like someone opens the website and goes to the client then immediately this will start running and we can get a socket variable directly from here which can give us a lot of information for example we can console log into our server whenever a user is connected i can say something like user connected and then put the like the curly braces and say socket dot id we can put the id for the user so each user in this socket server will um receive a different id and we can test that out by coming over here i'll just i'm coming this out for now but opening our server which is this terminal over here and as you can see it's already console logging a bunch of stuff because we refresh the page a bunch but i can run this again and you can see that immediately a bunch of users is connecting now the reason for this is because we don't have some sort of exact way to um to protect it from connecting a bunch of times yet but as we write we go you'll see that it will only connect the same amount as people who actually go into the website but you can see at least we're detecting whenever someone goes into the website like if i open up a page incognito which is something i'm going to do right now here it is i have a page in incognito and i have a page not in a cognito i'll actually just refresh both of them like i will you'll see you can count how many users are over here but if i refresh the page over here once we get another user right if i refresh the page over here once it should console log another user as well so it detects how many users are actually logged in into our server so then what we can do is we come here to our index.js and this is just a way for us to measure um if the server is running what really matters is that now we can use this circuit variable to listen to specific custom-made events so imagine we want to emit an event when you send a message let's call it um send message something like this i'll say socket.emit send message and obviously over here we can send some data by putting an object over here that will be sent in this event now how do we get this data well we can do something like um i don't know like creating some states which is what we're going to do and then just grabbing the data from the input and then using that data to be sent but for now let's just put some fake data we'll send an object with a property called message and a value called hello something like that then save this then we can come to our back end which is this over here and just say socket dot on and we'll listen to an event called send message then this event obviously will return some data so we'll create a function over here a callback function which will receive that data and when we receive that data we can do a couple stuff we can for example console.log to check if we're actually receiving the correct data and i hope we are so let's open our our terminal and let's click on on the send message button and as you can see we do get the correct message right it is listening to the event it is emitting the correct event but what we want to do now is instead of console logging the data we want to emit this back to everyone else who is connected to the server now we can send it to just specific people and i'll show you guys that in a second but for now let's just broadcast to everyone who's connected to this socket server um the message that was sent by one of the users so to do that we'll say socket over here dot broadcast and broadcast basically allows us to send something to everyone but yourself so if i omit this event it will be sent to everyone but i won't receive it then we say dot emit and we'll emit another event and we have to give it a different name so this event will be called receive message and like the name says we'll be listening to this in the front end so that we can receive all the messages that were emitted by other people now what we pass here is the data that was sent through the front end right and then in the front and again we can listen to this event somewhere over here now how do we listen to this so the way we listen to this event is by actually creating a use effect hook that we're going to import from react up here at the top so i'm going to say import from react like this and i'll import the use effect hook and this hook will be called whenever there's whenever we receive a message so it kind of serves as a as like a function that will run every time any event is thrown to us on the socket io server and the reason why that happens is because i'm going to pass the socket variable inside of the dependency list in the use effect so that whenever an event is emitted then this function will run again so what we put inside of here is we basically say that we're listening to an event in case it happens and the event we're listening to is the receive message event like this and this event similar to the back end will receive some data so we'll put a callback function over here and grab the data and for now what we can do is we can do something like alert uh the message so i'll just alert the message the data the message and let's see if this works so i'll come over here and i'll click i'll just write a message and actually it's not catching anything right here it's gonna just send hello but i'm gonna click on send message and as you can see on another browser i receive the alert saying hello which is amazing so i'm gonna click ok and um i'll try with this one if i click on this one you can see that now on this one i receive the alert so it is working um these are completely different browsers one is incognito the other one is not so you can see people on different computers if this is deployed um would be able to receive the the same data right you can even test this out by opening the project in your phone and trying to send data from there i've done that a couple of times and it works out perfectly now one thing we can we can try is instead of just alerting a message i want to be able to now how exactly is this working i just want to do a really quick recap of of how the like what is the flow of the of the project because um i know it's kind of confusing so like i mentioned the back end will always serve as a layer because you can never you when you emit a message or emit an event from the front end you can only admit it to the back end um but technically that's not what we want right i want to emit an event i want to send data to another user not to the back end however in order for socket i o to work you got to do it this way this is kind of like a a work around to it you emit the message to the back end then the backer will be listening to an event that you will be emitting in the front end you'll send the data then the backend event will rece will be listed that you're listening to will receive that data and then just emit that to another event that has been listening to in the front-end so we listen to the other events in the front and get the data and do something with it so that's kind of the flow right you need to create um two different events to send um some data so then what i want to do here is instead of just sending hello i want to do something a little bit more complicated where i basically create a use state over here and i just create a state like this const message and set message it's just so that we can actually grab whatever the user is typing on the input set it equal to use state and it will be a string then i want to be able to use this as a message over here and since it's the variable and the key are the same we can just delete this and just pass the message like this then i'll grab this set message function over here and on our input i'll put an unchange that will be called whenever there's any change in the input so whenever we type anything in the inputs and all it will do is it will set the message equal to the event that we're going to grab from here look at this event dot target dot value like this now save this now uh what we can do is uh we're grabbing the correct event and it should be working but we also want to be able to display this message like a text in the in the ui so i'll create another state over here called message received like this message received then set message received and we'll set this equal to use state and will also be a string and this over here will basically be the message that we receive from um the other user so put an h1 tag over here saying something like message and i'll just display the message down here message to receive now how do we actually set the message to be the correct message well when you or when you listen to the event and you receive the message from another person you just set the message received equal to data.message like this now let's test this out let's come to our both um browsers on this one i'll just type hey wassup hello something like this i'll send a message and you can see this user received the message now it's alerting something because i i forgot to refresh the page so some of the changes are still active but now you can see that if i tap another message it just sends the message to this one i can type this as well over here and they will receive the message over here so you can see thousands of different use cases for where where this would be useful it's just emitting different events that we can receive and send actual data in real time so this is really cool and one of the basic use cases is some sort of messaging system so what i'm going to show you guys is how to actually send messages um to specific people so i'm gonna show you bring up some code for that um and i'm gonna go over the code so that you guys can get an idea of how to do that so i just wrote the code and i'm gonna show you guys an example of what i'm talking about basically imagine you're in a scenario where you have three people right so to test this out all i did was i just opened three different um like browsers three different tabs it doesn't have to be one like incognito or not just opening a different tab is already fine but you can see there's three different instances of our client right our front end so now you can see there's there's a difference there's a little button and an input called room so what is a room and socket io well a room it's almost like a channel it's it's a specific closed door um place where you can send data and only people in that place will receive that data and are able to send that data so this is great for creating private messages for creating teams or something like discord where there's private servers that kind of stuff right so this is a simple example but imagine you have three users and only these two people want to talk to each other so they can put a room number obviously you can mask the fact that you don't need to spec they don't need to specify which room they're joining you can just like do create a room like internally on your code where just between two users but in this case to keep it simple let's just let them specify which room they want to join so let's go like join room 23 i'll click join room then this one let's join room 23 as well join this room this one let's just join room 99 so it's a different room right so they're all in different rooms um let's send a message from this one saying hello world and as you can see if this is working only this user should receive a message because he's the only one who is also in the room 23 and as you can see that's exactly what happened this one as well if they send the message saying this is a message only this one should receive because this is the only other person in the same room and this is what works now on this one over here if it says i'm alone and sends a message none of them will receive because no one else is in with a room 99 but if they change their room to room 23 and they send i'm alone you can see now everyone in the room 23 will receive this message which is amazing right this is simple to implement and i'll show you guys the code right now so the way you implement this is as following so first of all you'll need to create there's this event in socket io called a join event right so basically when say socket.join you're specifying some sort of value like a number or something like that uh where it's the id of the room you're joining so you're joining a room when you call this function so a way we can like the way we did over here is we created this event called join room and on the back end we're listening to it and when you receive when it listens to it it will just join a room with a specific room that is sent in the front end and in the front and over here there's this function called join room where it will just emit that event and send the room that the user writes on the input so we created this state called room and it changes depending on whatever the user writes on the input as you can see over here and then they click on the drawing room button and it just emits an event to join that room so they will join the room by doing this very simple like it's like 10 lines of code now how do we specify that the message is only being sent to their room well on the front end on the send message over here we not only send our message whenever we write it on on the input but we're now also sending which room we are in because we need to specify to who we're sending this message to so in the back end now instead of broadcasting the message on the send message event what we're doing is we're saying socket to then to the room that we want to send this message to and then we're emitting that so the to function over here is just specifying where you want to send this where you want to emit this event so we're only admitting this event to the specific room that we are part of so this flow is really nice i like it very much um it's so useful for so many use cases you can do so many things with it you can do a multiplayer games with this you can do um chat apps like i mentioned you can do um discord clones whatever you want there's so many use cases like notifications as well it's really nice but it's just nice to see something like this and i wanted to go over this because i feel like whenever i make a video uh using socket io inside of a project it's never the main focus of the video so for that reason i wanted to take this time to just explain to you guys the library and explain the idea of websockets so you guys can get a better idea of it so with that in mind i'm going to leave all of this code in the description you can just check it out and play around with it however you want i really appreciate you guys watching this video if you enjoyed it please leave a like down below and comment what you want to see next because i'm posting once or twice a week i would massively appreciate if you guys could help support the channel and yeah that's that's basically it really hope you guys enjoyed it and i see you guys next time [Music] [Applause] [Music] [Applause]
Info
Channel: PedroTech
Views: 148,135
Rating: undefined out of 5
Keywords: javascript, learn reactjs, nodejs, programming, react tutorial, reactjs, reactjs beginner, reactjs tutorial, typescript, react js crash course, react js, node js, express js, pedrotech, traversy media, traversymedia, clever programmer, tech with tim, freecodecamp, deved, pedro tech, sockets, web sockets, socket.io, socket.io react, socket.io tutorial, socket.io node.js tutorial, socket io, react chat application, react chat app with socket.io, react chat app firebase, node js express
Id: djMy4QsPWiI
Channel Id: undefined
Length: 32min 34sec (1954 seconds)
Published: Tue Mar 22 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.