React JS: How to use MobX for State Management

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey guys today we will be looking at something a little bit different um it's going to be something about global state management in react so there's quite a few libraries that you can use to help you with this you know the first thing is the react context api so the basic definition what we're trying to do or what we're trying to accomplish is provide a way to pass data through component tree without having to pass down props manually at every level so this is a very basic description of what is the point of doing something like this and obviously context api will be the easiest solution for you but there's quite a few different reasons why you might want to use something other than the context api we won't get into those because obviously you're here to learn about mobx but i just want to give you some alternatives there's there's also the very popular react redux which is used by many companies which you can learn more about on this page but what we're going to be looking at is the library called mobx so what we'll do is go to our application here and it says add your code here so i just have a simple very simple application um with the header body and an error boundary so we're going to actually create a new component here so i'm going to create a new file called to do list tsx and in here we will import react first of all and then we're going to create a component called to-do list and this is a very popular problem to solve if you want to try something new so this will be a function component and we'll just return a div for now to do list and to add add an interface to our props we will just create an interface called to-do list props which will be empty for now and react.fc is actually a generic type so you can pass in to-do list props inside of this and it'll add it to its own props all right great so let's go to our app component and let's add our to-do list okay so now we have our to-do list right here so let's go ahead and update our component so what we'll add here is an input first of all to actually add to our to-do list and right next to that we will create a button for you know adding it to the list just call submit and the type here will be text and obviously to store to in order to submit with our submit button we need to store the state of our input element so we'll create a state variable in our component using use state and this will be of type string and you may not want to add a type here because it it'll be inferred by the default value in the use state but it's your preference this will just call value and set value so if you don't know how use state works is it returns a array of two elements in it so the first one will be the actual state of your value and the second one will be a function that you can call to set the value so that's perfect for us because the value here needs to be a string and when we when this changes we'll call on the on change hook which will be a function which will take it have an event in it so this event if you hover over this one it'll say that it is a react dot change event which gives us the property for setting the value which will be in event.target.value so let's clean this up okay so we have an input box which is now controlled so that means we are controlling the value and how it changes with with our state so the only thing left now is to add on change handler to our submit button let's just see if all this works fine and we don't have any errors okay all that looks good the input element updates and submit does nothing and one thing we should change is this should not be on change it should be on click so that when we click the button this but this function runs um but what should we actually do in the on click well we need to add it to our add this value to our to-do list we don't actually have a to-do list so let's create a new file for that and we'll call it to-do store because we don't want our to-do list to live in our component we actually want it to be centralized in a store so we'll create a simple class for this called to do store and inside of here we'll have one variable called to do's which will be an array and it'll be initialized to an empty array but we don't actually have a type here so instead of keeping this as any array we should make an interface for our to do items so this will be a to do item which will be which will take an id and that'll be a number for now and the title of the to do which will be string and a completed which will be boolean so instead of being in any type this will be to do item and all classes in mobx should have a constructor so in this constructor we'll actually use a method from mobx called make observable and that'll get auto imported from mobx which will take two arguments one is the instance of your store so that will just be this in this case because we have a class and the next argument will be an object with all your ins with all the properties of your instance so in this case we just have one called to do's so to do's will actually be an observable and that should be imported from mobx as well other than that we do need an action so an action is anything that mutates your state so in this case we need to add a an action called add to do which we'll just take a title for now so just a string and we'll create our to-do item called item which will be of type to do item and the id i'm just going to create a random id and this is probably not the best way of creating an id because it could be duplicated or it could we could have multiple of the same ids you should use something like a server side id in this case and the title will just be the title and completed will always be false when you first create the item so we should now also add it to our to do list so to do.push item so what you'll notice we are actually mutating the to-do's array now this is one of the benefits of using mobx you can say that in things like react redux or the context api you are not allowed to update any of the props so instead of creating a new array and adding it to the new array and then setting the to do's array to that new array we are actually just pushing it to the same array and mobx will take care of informing all of our components that to do's array has been updated and the last thing we need to do is make sure that add to do is is in action so we can give it a type and we also import this from mobx so to do's is an observable which comes from mobx add to do is an action which mutates the to-do's array which it comes from mobx as well and so the last thing we should do is to the store should always be a singleton unless you want multiple instances of the store but in our case we're just going to create an instance or single instance so we'll call it to do store and we can actually call it the same thing so call this one to do store implementation and change that right here so we'll always use this instance of the to do store all of our components will look at the same to do instance for our to-do list the way we'll interact with the store is we have via props so in the props we'll take a to-do store which will be of type to do store implementation and we'll destructure that right here to do store so that we can use it and inside of our app we just need to pass it down so in this file we'll actually use the instance that we created which will be to do store so the first thing we can do is inside of our to do store we can add a add to do which will just be the value so whatever value is inside of this variable will will add it to the list and to actually view the array of to do's we'll create a ul and map over the to do items so to do store dot to do's dot map which will give us and here we'll just return an li with the name of the to do or title so let's just type in something and press submit no so now nothing is actually happening so why is that we we are looping over the list here and we're on change we're setting the value to the state and on on click of the button we're adding it to the to do so the problem is even though we are looking at the store component we're not actually create making this component and observer of the store so this component does not have any idea that something has changed in the to do store because remember the to do store does not change it's always the same instance it's the properties inside of to do store that are changing so mobx actually has a observer or actually mobx react has an observer higher order function so this will actually we should actually pass an r component into the observer higher order function and then it will make sure that everything from the store actually gets updated as a prop so now now that we have wrapped it in the observer function we should be able to see our changes so since i pressed submit so many times we have so many new to-do's added but if i refresh now and type in one and press submit once you can see our ui is updated so we can actually keep going and add new functionality one thing that you should probably add is we can have a function for to do or toggle to do which will take an id which is a number and it will just toggle it completed true or false so the first thing we can do is get grab the index so we'll grab the index by the id which was passed in and if the index is more than negative one so it's a valid index we will say this dot to do's dot or index dot completed is is equal to the opposite of of this variable so we'll just add a sort of bang there and save that so remember whenever you add a new action we have to add it to the constructor make observable function call so we have a new action called toggle to do which is connected now we won't actually see anything update on the ui because we don't really have anything that says that it's completed so i'll just i'll just create something here that can tell us that it's actually been completed we can check if to do dot completed then we will render an x otherwise we will render a space so when whenever we click on the li we can call something in the to do store just like we did here add to do so what we can do is to do store dot toggle to do and here we will say to do dot id we will add one two and when we mark them completed it actually toggles it it's very weird that this does not go away so i can just keep clicking the if statement should actually be right here so if value exists then we do something otherwise we do nothing and the the other nice thing about mobx is that you can see i've updated the code and this has refreshed with the new functionality that i just added but our our store is still there and our store does not reset which is rare to see in most so you can see that this one was a hard refresh so last thing i wanted to show you is something called a computed value computed value it does not actually change the store but it gives you more information about this sort of store so to understand this we can add something called completed and this will just show a number on how many to do's we have completed and the next thing might be remaining so how many to do's you actually have remaining so let's try and compute that from in our to do store so we'll add a new method called get completed or get status and this will be a get method so so this is actually a get method not a regular method so from within this method we actually want to return an object with completed and remaining so we'll create two variables one call completed and initialize it to zero and one called remaining initialized to zero and then we'll loop through our to-do's list and if to do dot completed is true we will say completed plus plus otherwise we will say remaining plus plus and at the end we will just return one single object for completed and remaining so this get status is is there and it will work but it is no longer it's not actually registered up here so we'll say get status or actually just status and this will be a computed which will also come from mobx so now what we can do is get that value whenever this component renders so we'll get the status equal to do store and the way you access a get method is just by the property value so just like you would use any variable inside of to do store you can access it just like that so here what we can display is status dot completed and here we can display status dot remaining and let's add a line in in the middle here and if i go up here and add one so now we have remaining one and completed zero so if i keep adding more and more this also updates along with our component and if i mark one off this automatically updates up here so computed values basically give you more metadata about your store instead of changing the store so those are some of the basics that you should know about mobx and how it can help you create your application and be more flexible so you can use this to do store in any part of your application and the three main ideas in modbx are that variables are observables and to update your observable you need an action and the computed values are basically computed out of your store without actually updating the store so if you have any more questions or if you'd like to see more content about mobx please let me know in the comments down below and please subscribe if you want to learn more about javascript front end and everything related to that
Info
Channel: AmanScripts
Views: 14,156
Rating: undefined out of 5
Keywords: mobx tutorial, state management, react, reactjs, javascript, typescript, UX, user experience, interactions, input box, learn react js, create an application, web developer, frontend development, programming questions, programming interviews, javascript basics, learn javascript, useState, useContext, React Hooks, localstorage javascript, react hooks, web development, context api, API Response, REST API, JSON, Parsing, Weather Data, Tutorial, CSS3 tutorial, react js, react tutorial
Id: 2ejs-uxSbAk
Channel Id: undefined
Length: 16min 59sec (1019 seconds)
Published: Tue Nov 10 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.