loading...
Cover image for React State for Dummies - How was it before React?

React State for Dummies - How was it before React?

mustafaanaskh99 profile image Mustafa Anas Updated on ・7 min read

Hello everyone and welcome to my first tech blog ever! It took me a lot of time and hesitation to decide to sit down and start sharing any bits of information, but here I am attempting to write and hopefully strengthen the tech's community's knowledge anyhow!

This is part of a series of articles in which I try to break down the evolution of React State concept and try to showcase its importance by explaining the problems React State tackles in simple and intuitive way.

What was all this about anyways?

Throughout the history of all programming languages, the aim was always to have a language that is as efficient as possible in creating/manipulating and reading/displaying data. Developers wanted to have an efficient and easy way to add created data to the DOM. React is one of the frameworks that achieved a fast and straight forward way of doing so.

In order to understand what did React State solve and why it is important, we need to put ourselves in the shoe of the pre-React developers and see how they used to deal with creating data, saving it in the DB, and adding it to the DOM.

Let's do it the jQuery way!

Well, we will be using Vanilla Javascript rather than jQuery but the following code uses the logic that was very common between jQuery developers.

In this example, we will be saving a student's name in the localStorage of the browser and displaying it in our page. Let me begin by adding the HTML code.
(As I am not the best UI designer, I will use the help of Bulma.io just to make things a bit more appealing. All you need to do is run npm i bulma in the directory where you will be creating the files we create in this tutorial, then you can follow up with me and get the same result.)

<!-- main.html -->
<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.min.css">
        <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script> 
    </head>

    <body>
        <section class="section">
                <div class="container">
                    <h3 class="title">Student:</h3>
                    <ul id="li" class="subtitle"></ul>
                </div>
                <section class="section">
                    <div class="container">
                                <div class="columns">
                                    <div class="columns">
                                        <div class="column">
                                            <input  class="input is-success" id="submit" type="text" placeholder="Student Name"/>
                                        </div>
                                        <div class="column">
                                            <input class="button is-success" type="button" value="Submit Student"/>
                                        </div>
                                    </div>
                                </div>
                        <input class="button is-warning" type="button" value="Clear Storage" />
                    </div>
                </section>
            </section>
    </body>
</html>

The first div that has a Student title and an empty ul as a subtitle is where we will be displaying our student name. You can see the following in the code:

<ul id="li" class="subtitle"></ul>

the list has an id because this is how we will access it to append the student name in it as a list item.

When you first load the page, it should look like this:
Alt Text

By clicking the Submit Student button after filling the input field, I want the name to be saved in the localStorage then appear right below Student:. By clicking Clear Storage button I want to delete the saved name in the storage then delete it from the page.

to keep things clean, lets create a seperate main.js file and link it to our main.html page.

I will add the following line to the bottom of </body>.

<script src="mainInitial.js"></script>

Saving the input in the localStorage

Now we need to create a function that runs when the Submit Student button is clicked. This function will take the value of the text input and saves it in the localStorage with a 'student' key.

// main.js
const saveStudent = (val) => {
    localStorage.setItem('student', val)
}

I will go to main.html file now, pass the text input value to the function, and run it when the button is clicked:

<input class="button is-success" type="button" value="Submit Student" onclick="saveStudent(document.getElementById('submit').value)"/>

Now our code actually saves the data in the localStorage of the browser. It just does not display it yet. You can try adding any random text and navigating to the localStorage in the storage in tools.

Reading data and displaying them

Remember the ul we gave an id for at the beginning? now we will grab the saved name in our storage, grab that list by its ID, then and append the name in the list as text.
Lets write an if statement that checks if there is any saved student in the localStorage and display it in the page. If not, we will display a text that says: Storage is Empty.

// main.js
const locStor = localStorage.getItem('student')
if(locStor == null){
    console.log('Storage is Empty')
    document.getElementById('li').append('Storage is Empty');
} else {
    let student = localStorage.getItem('student')
    document.getElementById('li').append(student);
}

Now if you run the new code in your browser, you page should look like this and display the last name you submitted:
Alt Text

and sure, if you did not submit any name yet, it should show the following:
Alt Text

Now before we move any further, to delete the saved name, lets create a function, clearStorage(), that clears the localStorage.

// main.js
const clearStorage = () => {
    localStorage.clear()
}

lets go back and link the button to the function:

<!-- main.html -->
<input class="button is-warning" type="button" value="Clear Storage" onclick="clearStorage()"/>

YAY Now we can add data to the localStorage and display it in the page! ... but wait a sec, there is something missing.

As you may have noticed, every time you submit a student name, you will need to refresh the page for the new name to be displayed. Same for clearing the storage, you will need to refresh in order to see the Storage is empty in the page. If the type of Submit Student input was type="submit" instead of type="button", the page will refresh on its own and you may not notice it. Anyways, we could instruct the page to reload every time we submit a student name but do we really want to do that?

Efficiency in displaying newly created data

In this example, we were only adding and deleting a one-line text. Even if we are to refresh the page every time we update the name or delete it, it will take no time, but this is not always the case. Imagine if we were adding hundreds of students information to the page, or thousands, or even more, it would be very heavy and not efficient to keep on refreshing. Instead, we will manipulate the DOM.

Lets start with adding data. Every time we click the submit button, we want to save the name in the localStorage (something we already did). Now since we will not be refreshing the page, we need to add this name immediately to the page (before we even send it to the localStorage) in order not to have to grab it from the page once again (less time -> better efficiency).

This is how we do it,

we will update the saveStudent function to the following:

const saveStudent = (val) => {
    let newStudent = document.createElement("li")
    let studentName = document.createTextNode(val)
    newStudent.appendChild(studentName)
    newStudent.setAttribute("id", "new_student")
    document.getElementById('li').append(newStudent);
    localStorage.setItem('student', val)
}

As you can see, we created a new li, then we created a text node that holds the name of the student, then we appended that node in the list item we just created. Before we stored the name, we appended it in the ul we have in our main.html file.

We made it! and now, the data stored in the localStorage and the displayed data are kind of synchronized. They are identical and our page looks just like if we would have pulled the data from the store, except we made it shorter and more efficient (Yes it is such a hustle, but this is what React State will tackle later as you will see).

If you noticed, while creating the node that holds the student name, we gave it an id that is "new-student". This is just so we can access the item and delete it easily when we want to clear the storage. Lets do that!

const clearStorage = () => {
    document.getElementById('new_student').remove()
    localStorage.clear()
}

Now if you try adding a student or clearing the localStorage, you will notice that it happens smoothly without having to refresh the page. However, this not very convenient or easy to do. Keep in mind that in this example we are only working on one list that has one name. Code with such techniques can easily get messy when dealing with bigger data and arranging it in tables or graphs or so.

React state came and provided an alternative, easy, and very convenient solution to this problem. It provided the State object. In simple words, state is just a Javascript object that can store whatever data you want it to store (in the page itself only). Changing any of the data in this object will tell React, uhh, the user seems to be updating the page!. React then goes and checks what data was changed and where was it used. Then it only re-renders (refreshes) the part in which the changed data was used. This eliminates the pain you have to go through while manipulating the DOM to display the correct data, and at the same time it does it efficiently without refreshing the page and reloading all the already displayed data.

In the next article I will be developing the same example using React state and proving how much pain it saves you :D.

Thanks for reading.

Posted on by:

mustafaanaskh99 profile

Mustafa Anas

@mustafaanaskh99

Full-Stack Web Developer. main stack: MongoDB, Expressjs, Reactjs, Nodejs, and GraphQL (some React Native and Flutter too)

Discussion

pic
Editor guide
 

This is a great first blog post! Good work. I think it will make a good series too - great for breaking down a complicated idea, and explaining why it exists.

Good luck on your future writing!

 

Thank you Chris for the support!
means a lot

 

Initially I didn't understand exactly why we required state in React, this was incredibly helpful to me.

Thanks a lot!

 

I am glad I was able to help <3