How State Management Works in React Native vs React

State Management in React Native has similar options to React.

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

This lesson preview is part of the The newline Guide to React Native for JavaScript Developers using TypeScript course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

This video is available to students only
Unlock This Course

Get unlimited access to The newline Guide to React Native for JavaScript Developers using TypeScript, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course The newline Guide to React Native for JavaScript Developers using TypeScript

React provides a way to do state management at a component level. And depending upon what we have chosen to build, that is a class component or a functional component, the implementation can vary. We'll look at both of these in this particular lesson. What we'll do is we'll implement the search screen, and we'll do a class based implementation and see how it manages state for its own view. And we'll also do a functional implementation for the same. So let's get started. States are basically controlled in any component in React, either through props or the state variable that the class component has. Now props don't change over the lifecycle of a particular component. They are basically the variables or the values that are passed through to the component as inputs. And states are what we declare internally in a class. A very simple example can be that features declare a state variable. This is already available if we extend the class by react.pure component or a component. And then we can declare anything over here like we have a double. And then in the redder function, we pull the variable from the state. Then based on that, we assign a condition to render something. And how we change the value of the state is there's an input function that's called this.setState. And we just pass the value to the variable that needs to be changed. As soon as this happens, the function will re-render itself. So that is quite straightforward, right? We just have a state variable and we assign whatever we want to and whatever we want the component to watch for. And whenever that changes, the component will re-render. So where it gets a little complicated is if we go back to the lifecycle of any particular React component. So now we should not be doing any set state in the render phase of the component. What that means is that if we do a set state inside a constructor or other red der function that will make the component render infinitely. The reason for that is when we do a set state, the render function is called. Since the state of the particular component has been updated. So that makes it an infinite loop. Now we can also do set state inside a component did update, but we need to add an if condition. Component did update is called just after the render function is called. Anytime, whether it's the first time or the subsequent times. Now, if we do a set state inside that without an if condition, what that basically means is that the lifecycle will keep going on in a loop. As the set state will call the render function and after the render function, the component date update will get called and it will keep going on and on. So that's where we need to be a little careful about. Otherwise, it's a pretty simple implementation. So let's look at that. Let's try to save the values that we enter over here as recent searches. What we can do is we can simply declare a state inside our constructor. So we'll just say this dot state. We already have that variable and we'll say recent searches and we can declare that as an empty array. And whenever a user enters something and click submit, we'll see if that as a research search. Going forward, we also might want to save that in a permanent storage in the app. We'll look at that in the AC storage module. Now let's say that we wanted to save a user's recent searches on the server side, right? And whenever we load the search page, we want to fetch that data. So component date mount is the best place to fetch any server side data. This is called immediately after the first render. And if you want to make a network call to get a data for that particular screen , this is the best place to move that. And right here, what we can do is once we make the call, we can also do this dot state and that will trigger the tree render. Now what that also means is that the render function is initially called without that network call. So the function needs to also handle that scenario. Let's say that the page is trying to render recent searches, but it will be called before the network call. We need to handle the scenario where we don't have the research searches from the network data yet. Next, let's try to save this recent searches. So what we'll do is we have this input box. And as soon as we click submit, we'll save that to the recent searches and display it on the page below. So it is to that for that we need to add one property to the input box. Let's go to the input box. Now, we want to save the value whenever the user clicks, go or submit in that. So let's say that we type speakers. And when a user clicks return from there, then we want to save that. So how we can do that is the text input takes a property that's called on submit, editing. This basically is like the submit on a form and it's called after user presses a return or whatever the button is there. Let's declare that as props for this and expose it. So we'll say on submit and let's declare the type. On submit event, let's make it non mandatory. On submit. Now what this gives away is a native event. So we'll declare that type. So if we click on submit editing, we'll see that it expects a. It provides a native synthetic event, text input. We can simply copy this over. And that should work for us. So now we'll just expose that. We will say. On submit. And we'll pass that now our text input also supports passing in on submit. So that is great. Let's go back to the text input and let's pass that we can copy those types from there. And we can pass that to. On submit. And we can pass that to. On submit. Now we go back to the search page and we go to the header component and we say that we need a. The search input now takes an on submit. Now let's declare a handler for that. And what we get is a dev event. And the value will be inside a dev event dot text. So let's declare native. Send it a event and. Text input. Submit event data. Now what I've also done is I have launched flipper. This is a debugger tool. So it's quite simple to use. We just need to install it and as soon as we launch it, if the Metro bundle is running with an app, it will automatically pick that up. Now it's useful for a few things like looking at the logs. This is the log that we have that we can also see in the Metrobundler. It's same running drawer, home and search. But this is a more cleaner interface and reactivity. But also does this. But apart from this, it also tells us the layout. So we'll look at how to use paper in detail in the upcoming modules. For now, we'll interested in the logs. So we'll use it for that. Now on submit, we have our text. We'll save that and should also save this. Once we refresh our app and we press enter. What we get is the text. Now what we need to do is we need to save that in the state. Now we have two options here. Either we ask the header to save the values with itself, all the recent searches or we can pass this value to the parent and ask them to do whatever they want with that. Now what we'll do here is as soon as someone presses an enter, we'll make a request, a network request. We'll do that in the module that we'll talk about making API calls. We'll make a network request for that and show the results over here. But we also want to save that as recent searches. How we can do that is let's pass that to the parent page for now. So how we can do that is we'll declare the on submit method. On submit and we can say on submit event and let's just copy that over. So now on pressing the return, we'll pass this value to the parent component. Let's comment this out. I probably will copy this over to the parent component. So we'll go to search and where we are passing the header, we'll say. [ Silence ] And we'll pass the submit to the header. [ Silence ] Now we have the value over here. What we can do is we say this dot set state and then we need to just pass it to the recent searches. So for that, we first get the recent searches. [ Silence ] From the state. [ Silence ] Okay, we need to declare it. So we'll say recent searches and it can be an area of string. Let's keep it simple for now. We'll say recent searches and we'll say recent searches dot push and we'll push the value that we are getting. And we'll set the recent searches to recent searches. So as soon as we do that, we should have the value in the. So let's save that and let's also see if the value is being set or not. So set state, it takes a second function and that basically is a callback. Once the application is done setting the value of this particular variable, it will give a callback where we can execute whatever we want to. So right here, what we can do is we can do console dot log and if we check the value this dot state dot recent searches. We will see that whatever type is getting saved into this. We'll say speakers and we press enter and we see this dot recent searches as speakers. So now let's also go and search for something else that say headphones and now it has speakers and headphones. So that's quite simple, right? And remember every time we are doing a set state, it's also again calling the render function. And we can put a console to check that. We will save that and now as soon as the view was loaded, render was called and we say speakers. It is doing that render is called and then the callback happens. So we can clearly see the life cycle over here and similarly for headphones. Now we have the values all we need to do is we need to display it. We will say that in the function will say const. We'll get this from state. Now remember initially this will not have any values and just an empty array. So if you want to display this as a list, we want to put a check on that. We'll say recent searches dot length greater than zero. Only then do you render this particular block. So we'll say recent searches dot map. And now this is the search term. Let's just do a simple view on this one. This is just to demonstrate. And we'll say search, let's save it and we'll do a ctext. So we'll use a standard text. And we do save. Now let's say speakers and we can see the speakers there. And let's do headphones and we get the headphones there. This can have a title. We could probably add a section title for that. Let's just do section title and we can say title equals. Recent searches. Now see as soon as that time you will refresh, we lose it because this is getting stored in the corporate state. We do speakers and we do headphones. So next let's look at the other lifecycle events of a class. As I mentioned earlier, component did not is great for making any network calls or doing any side effects that we want, like pitching data from a sync storage or API or something else. And we can do a set state over here. Should component update should be avoided. What this basically requires is it requires a Boolean return. What this is going to provide us is with the next prop and the previous props and we can compare them and see if the values have changed or not. And then avoid additional vendors. This should mostly be avoided and the recommendation is to use a react pure component class. And as soon as we do that, we'll also see a warning on the UI that says search has a method that's called should component update and it should not be used with a pure component. So what pure component does in react is basically does a shallow comparison of the attributes of the props in the state. And that's a great way to avoid any additional renders that are not required. Next, we also have component did update. This is called after the render function. We're going to make network calls over here. If you feel that the props that have been passed to us require a certain update to the UI, like for example, we get a different user ID and we want to fetch the data for that. We can do that over here and we can set state over here to not just one other condition is that this function is called after every render function. So it is a mandatory practice to add an if condition to it because if we don't do that component update is called after the render function and then the set state will trigger again or enter. So we'll end up in a loop. Remember, if you want to use component did update to compare any props of previous states, we have to use an if condition. Apart from that, we also have the component will unmount. And this is called just before the view is unmounted. Generally, there's not much that we can do here. If we do a set state, it's not going to matter because the view is already getting unmounted. One thing that it's useful for is cleaning up any methods such as invalidating any timers or events that we have subscribed to or canceling any network request. So that's the state management with the class. Next, let's look at how we can achieve quite a similar functionality with functional components. Next, let's look at implementing the same using the functional component and we 'll be using hopes for that. So, let's look at how we do it with the functional component. There are a lot of different types of hooks. We'll look at the use state hook and the use state hook. So, let's look at how we do it with the functional component. There are a lot of different types of hooks. We'll look at the use state hook and the use effect hook. Those two help us achieve the same functionality and the same lifecycle that we had for a class component and covered most of the use cases. And it's generally a good idea to build at least most of them as functional components and use hooks as much as possible. Though in my practical experience, when the view tends to get a lot more complicated, say a product details page might not be that complicated a scenario, but something like a cart page or a checkout summary page that shows all the different details of the different steps that are used as taken so far. I have found implementing a class a much easier solution. Now we had data that was coming from the previous screen, but we also needed to handle the use case where someone clicked a deep link and landed the page directly. Now the data that needs to be initialized for that page is either passed as props or fetched from an API based on where they are really being requested from. In practical scenarios, some of these screens tend to get complicated and having a class implementation is not a bad idea. So if you see yourself in planning towards a class implementation, then that's totally fine. Let's look at the functional components. We had a variable called recent searches that were declared in state. Let's declare that using a hook over here. So what we'll do is we'll first convert this to a regular function and we'll say const will use use state hook because we want to declare it with an initial value and the initial value is going to be at empty array. So what did I just do here? Basically whenever we use a use state hook, it provides these two variables. The first one is a variable that will have the actual value. So it can be anything that we want. And the second one is basically a set state function specifically for that variable. If we look at a class, we had a set state and we did a set state on a variable. So we said this dot set state and then we pass the variable that we wanted to set. In this case, we don't need to do that. We just do a set recent searches and whatever we've passed to this is going to set to the recent searches. That's how we are declaring a state in a functional component. And we'll go ahead and use that. Let's also go ahead and pass the on submit function to the header. We'll say on submit. And I'll just copy over the function. It's going to remain quite same. And we'll not need most of it. So let's just remove that. We can simply set the value using this particular function that we have. And we just need to pass the value that we need to set. So what we'll do is first we'll use this spread operator for passing the existing values that this has. And we'll also additionally pass the new value to it. And this should set the value of recent searches to the new value that we want. Okay, we did not initialize the area with any value. So we need to tell the use state that what kind of value are we expecting. So we'll just say that we are expecting an area of string and that should fix it. Okay, once we save, we'll get the value in recent searches. Next, I think we can also copy over the rendering part. Let's save that. And we have the recent searches. Let's say speakers, we save that, we get the value and let's say headphones, we save that and we get the value. So that was quite a simple implementation with functional components, right? And if we look at it, it's much simpler than the classes. But like I said, for a really complex scenario, I found the classes to be more manageable than the functional components. Next, let's look at achieving the same lifecycle that we have of a class component in a functional component. So how do we achieve the same functionality of a class that is done using the use effect hook. So use effective to get place for doing any side effects like we had in component dead mount. So this is a good place to make the API calls. Let's say we want to fetch a data for a particular screen or get some data from the async storage. Now there are a few things to consider over here. The first is this additional parameter. Now let's say that we declare a use effect hook without passing any additional parameters to it. What that will do is it will execute the use effect hook every time. What that means is it will execute the use effect with the first time the functional component renders and also any time that there is a change in value of any of its variable using one of the set state variables. The use effect hook takes a second argument as the set of variables that it needs to watch for to trigger any changes to the component. Let's say that we are dependent on data or set data and we want to re-enter the view whenever those variables change. We should pass those as an array argument to the use effect. And what the use effect hook will do is whenever there is a change in any of the values of the past variables, it will trigger whatever is inside the use effect. If you pass an empty array, the use effect will run just one time. What that means is we are saying that we don't want to watch for any particular variable. So now that use effect hook effectively becomes a component dead mount, which basically runs just once. If you remember from the class implementation, the component dead mount is called only one time whenever the component is mounted. So if you pass an empty array to use effect, we'll basically achieve that functionality. Now if you pass an array of values, the use effect will be called for any change in those particular values. So that is equivalent to calling the set state only variable in the class implementation. Now what use effect also allows is if we return a function from a use effect, this function will get called whenever the particular component is getting un mounted. So basically this will act as the component will unmount in a class implementation. So as you can see, use effect provides a different lifecycle events that we saw in a class implementation. Let's go ahead and test that. Let's just copy this over and we'll say that we want to use a use effect. So we'll say use effect and what we want to do is for recent searches, we want to watch over recent searches. And let's do this. We already had some recent searches that we wanted to fetch for that user. We will set that over here. Let's mark that. We will set set recent searches and we'll initialize this with some value saying. We'll call that and we are also pre-turding a function from that. We are simply doing an console lock for unmounting. So let's save that and let's go back. Let's clear this. And let's reload the view. So we'll go to logs. We'll see that we already have the render console over here. The reason for that is in reactative navigation. All the tabs are initialized as soon as the app is loaded. So basically when we open the app, the home tab, the search tab, the cart and as many tabs as we have, all of them gets initialized. So that's how we see the render over here and we only see that once. So that basically achieves our component did mount and we already had speakers set to it. So we see the speakers over there and let's say we want to add headphones to it and we can add headphones. So as we can see using a functional component, we can achieve quite similar functionality, what we had for class. A functional component also keeps things simple. And if you look at the overall implementation, it seems much more concise. The hooks were introduced not just because Facebook supports functional programming, but there's another great use case for that. And that is let's say that we have different views and we see ourselves rewriting a particular logic again and again. Like let's say that we had this logic to save the recent searches and then we were also going to save this in some kind of an async storage or a network. And this was a more complex logic. And in some other view, we were again finding ourselves doing the same thing again and again. We can also define our custom hooks and we can write our entire logic inside that. So this is a sample from the official docs. What we can do is we can write our entire logic and then we can simply reuse that hook in different views. That was difficult to achieve in a class implementation. Custom hooks allows us to do that quite easily. So we can define the view logic, not exactly a business logic and reuse those as hooks in different views. Just one thing to remember is that always take care of this second argument. Just be wary of that. Thank you and I'll see you in the next module. module.