DEV Community

Cover image for [ReactJS] The Basic of State and Props
Atif Aiman
Atif Aiman

Posted on

[ReactJS] The Basic of State and Props

Salam and hello! Yet, another write up about React!

And this time, I would like to write about some confusion faced by some beginners, the basic core that makes React an awesome framework. To start, I would like to go through the core of React itself, which is the language itself, Javascript.


Javascript

Since the born of Javascript, Javascript has been the "brain" of the webpage, that makes the web more interactive by allowing dynamic data, interactions and more flexibility in structuring data.

And so, since Javascript has powers in making the web awesome, we need to also allow Javascript to make changes to the page. Every browser exposes a global variable, called document to access the Document Object Model (DOM) of the page. When we want to insert the data, we just use the document object and modify the content, such as innerHtml.

<div id="title"></div>

<script>
var title = document.getElementById("title");
title.innerHtml = "Hello React";
</script>
Enter fullscreen mode Exit fullscreen mode

And so, that is how the basic modification of HTML DOM happens. Not forget, that in previous days, we are also introduced to AJAX and JQuery for more methods and utilities to access a different way of approaching variables. What a time!

And as usual, time flies, and people find out the potential of Javascript and brings it to another level - export the Javascript V8 engine as NodeJS.

So, the question here is, imagine if the data structure becomes so huge, and you need to monitor a lot of changes, so how do you manage the changes?

Initially, we had several ways. Setting up our triggers, so every time it is triggered, then the DOM will change accordingly. But there's a catch! If you don't do your trigger properly, you should expect unwanted behaviour. Another way is utilising event listeners.

// Event listener to specific element
element.addEventListener("click", function() {
  element.innerHTML = "Hello everyone reading this!";
});

// Event listener globally using `window` global object
window.addEventListener("resize", function() {
  document.getElementById("title").innerHTML = "Mr Worlwide!";
})'
Enter fullscreen mode Exit fullscreen mode

And so, that's basically how we do changes using Javascript and JQuery! However, here's the thing. As the project grows, you might want to consider several things for maintainability. And so, the Javascript frameworks were born to the world. AngularJS, MeteorJS, and ReactJS have their own way of dealing with these changes.


React: The Beginning

And so, React comes with some offers - components, and change handling using virtual DOM. To allow maintainability and code splitting, using the capability of Javascript itself, React is built to handle the changes in the background so developers can focus on crafting components.

What is virtual DOM, by the way? Instead of just relying on the DOM you are seeing on your browser, React will craft another DOM behind the scene, so when browser renders changes, you won't see any hiccups and see a smooth change.

Virtual DOM Replacing DOM using React

Am I using the correct meme? 😅

Here is the question. Since React is using virtual DOM, what tells React what the change is?


React: The State

Now comes the important part. What is the state?

We are talking about changes. So state serves a purpose to handle information about a component and monitor changes to the information within a component. Huhhh, the words.

Let me try to put it in an easier way. In this world (the web), there are a lot of humans (components), and everyone has their own information and purpose. So to store this information, we store it as a state. Name, age, your favourite food, your belief, your friend list, your eye open status. Anything.

const state = {
  name: "John",
  age: 21,
  favouriteFoods: ["🍔", "🍕"],
  friendList: ["👨", "👨‍🦱", "👲", "👳‍♂️"],
  isAwake: true,
}
Enter fullscreen mode Exit fullscreen mode

The state can contain anything! Numbers, strings, arrays, boolean, and even objects! So, this information is stored inside you, and only you will be aware of your own changes. Okay, the information is here, so how do we want to change this information?

In React, we want to make sure that changes can be monitored. So, the state shouldn't be easily changed, thus make the state immutable. So, changing the state directly doesn't work.

state.age++;
Enter fullscreen mode Exit fullscreen mode

So, how should we make changes to the state? React has setState to serve that purpose.

this.setState((state, props) => {
  return { age: state.age + 1 };
});
Enter fullscreen mode Exit fullscreen mode

This ensures that you and only you can change your own state, even your belief and ideals. Way to go, human ✊!


React: The props

We are living collectively in this big world. So, humans need to interact, so we can each do our own responsibility, and contribute to others. Like me writing this article, to convey information to you guys.

So, there must be a way that we can communicate. There must be a way I can tell you that my name is Atif. Unless I tell you so, you won't know that my name is Atif.

Props do that thing. Props can be seen as a medium for a component to pass information to other components.

There are a lot of ways for me to give you information. The words (string), the numbers (number), the set of information (object), the list of information (array), and even the instructions (functions).

const Atif = () => {
  return (
    <Reader message="Hello!" atifStatus={{ name: "Atif", isAwake: true }} />
  );
};

const Reader = ({ message, atifStatus }) => {
  return (
    <p>Hello, { atifStatus.name }!</p>
  );
};
Enter fullscreen mode Exit fullscreen mode

My question is, can props be changed? Well, it can, but only during me telling to you. Once it is conveyed, it cannot be changed by another component. Talk about the dangers of our own tongue! Once said, cannot be unsaid. Always think about what you want to say before saying it to others.

Well, back to React thing! So, referring to the above example, I can change whatever I want to pass as props in Atif component, but I cannot change the props inside Reader component. You can pass state as props as well!

const Atif = () => {
  const [name, setName] = useState("Atif");
  return (
    <Reader message="Hello!" name={name} />
  );
};

const Reader = ({ message, name }) => {
  return (
    <p>Hello, { name }!</p>
  );
};
Enter fullscreen mode Exit fullscreen mode

So, whenever I decide to change my name, then I will pass a different name. But Reader can only learn my name, and cannot change the fact that my name is as such. As I told you before, the state can be only changed by you and only you, no one else. The same applies to the components. Props shouldn't be changed.

Can props influence the state? I see why not!

const Atif = () => {
  const [name, setName] = useState("Atif");
  return (
    <Reader message="Hello!" name={name} />
  );
};

const Reader = ({ message, name }) => {
  const [care, setCare] = useState(true);

  useEffect(() => {
    if (name === "Atif") setCare(false);
  }, [name]);

  return care
  ? (
    <p>Hello, { name }!</p>
  )
  : (
    <p>Sorry, I am buzy!</p>
  );
};
Enter fullscreen mode Exit fullscreen mode

So what happened is, if I say my name is Atif, Reader will choose to not care, otherwise, it will greet as usual. That shows that props can influence the state! Even words can influence people motivation!


State and Props

So, these are things about states and props inside React:

State:

  • Each component monitor changes using state.
  • State is only defined by the component, and can only be changed by the component itself.
  • To change state, you need the method setState to change them, so React can detect it.
  • No component can read your state, since it is component-scoped. Unless you pass as a prop to other components.

Props:

  • Information that connects components together.
  • Cannot be changed upon accepting props. To manage changes using props, you can declare another variable, or state, or render method and change based on props.

So, that's it about states and props inside React! It might be hard to understand what states and props are since they both contain information and changes, but once you grasp the difference, and use it practically, it will be as easy as it gets.

The next question is, how about collective information about a group of components? Well, that means that we need a bigger component whose purpose is to manage those states, which is state management library such as Context API, Redux, Mobx, Zustand and others. But I think I will stop here.

Since these frameworks are created by humans, these concepts are related to the way how we live in this world, and that is how I see states and props.

Well, I hope this article clears your understanding of states on props in React (and possibly other frameworks as well!).

Until next time, peace be upon ya!

Discussion (0)