react use state hook simplified
| |

useState hook in React, simplified

useState hook is basically how React handles variables and keeps track of their changes.

When the value in the useState variable changes, then it will cause the components that are using it to re-render with the updated value.

Creating our base component

Let us start with the basics to understand how useState works. We will recreate the example of the previous GIF.

we’ll create a simple component in examples/SetValue.tsx

import React from "react";

const Example = () => {
  return (
    <div>
      <div>current value is: </div>
      <div>
        <button>Change to Orange</button>
        <button>Change to Apple</button>
        <button>Change to Banana</button>
      </div>
    </div>
  );
};

export default Example;

You might notice that I am using .tsx rather than .jsx, which is the Typescript version of react. Though, this tutorial applies for both of Javascript and Typescript.



import React from "react";

const Example = () => {
  return (
    <div>
      <div>current value is: </div>
      <div>
        <button>Change to Orange</button>
        <button>Change to Apple</button>
        <button>Change to Banana</button>
      </div>
    </div>
  );
};

export default Example;

and we will import it in our App.tsx



import SetValue from "./examples/SetValue";
export default function App() {
  return (
    <div>
      <SetValue />
    </div>
  );
}


the result for us is as follows:

useState

Now let us solve our problems bit by bit. Firstly, we want to display what kind of a value our variable has. So, let us create it and display it. In examples/setValue.tsx:


import React, { useState } from "react";
		// 👆 we will import useState from react
const Example = () => {
  const [fruit, setFruit] = useState(); // 👈 and we will initialize our 'variable' here
  return (
    <div>
      <div>current value is: </div>
      <div>
        <button>Change to Orange</button>
        <button>Change to Apple</button>
        <button>Change to Banana</button>
      </div>
    </div>
  );
};
export default Example;

The state and the function

let us disect the useState line in our example. It’s broken into two parts: the state, and the function that sets the value of that state.

      // 👇 this is the name of our variable
const [fruit, setFruit] = useState();
	     // 👆 this is the function that changes the value of our variable

Things to note out here is that you can name those constants anything you would want, and they don’t have to be following the same name.

Meaning, you can name them [fruit, setCake] if you would want, and it would still work from a functionality standpoint. But from a code readability standpoint, that wouldn’t make sense, right? so the conversion here is:

const [variableName, setVariableName] = useState()

now in Javascript, we would set an initial value for our variable like this:

let fruit = "orange"

the equivalent to that in React would be:

const [fruit, setFruit] = useState("orange");	

Displaying the value in our component

So now, what we have so far is a state with a defined initial value:

import React, { useState } from "react";
				
const Example = () => {
  const [fruit, setFruit] = useState("orange"); 

  return (
    <div>
      <div>current value is: </div>
      <div>
        <button>Change to Orange</button>
        <button>Change to Apple</button>
        <button>Change to Banana</button>
      </div>
    </div>
  );
};

export default Example;

what remains for us is to display it in our div, and to do that, we will be using {}. Using {variableName} in our div will allow us to display the value of our state in our div:

import React, { useState } from "react";

const Example = () => {
  const [fruit, setFruit] = useState("orange");

  return (
    <div>
      <div>current value is: {fruit}</div>
      <div>                   👆 this will allow us to display the value of the fruit variable
        <button>Change to Orange</button>
        <button>Change to Apple</button>
        <button>Change to Banana</button>
      </div>
    </div>
  );
};

export default Example;

this would display:

Great so far! we managed to solve our first bit. now our next problem to solve is to change that variable’s value. this is where setFruit comes in!

Changing the state’s value

We’ll start by creating an onClick handler for one of our buttons.

<button onClick={() => {}}>Change to Apple</button>
	      // 👆 remember that what's inside onClick must be a passed function, not a called one.

inside that arrow function, we will use our setFruit function.

<button
  onClick={() => {
    setFruit("apple"); // 👈 calling our function and passing the new value 												            // will change the value of the "fruit" variable
  }}
>
  Change to Apple
</button>

our code so far will be as follows:

import React, { useState } from "react";

const Example = () => {
  const [fruit, setFruit] = useState("orange");

  return (
    <div>
      <div>current value is: {fruit}</div>
      <div>
        <button>Change to Orange</button>
        <button
          onClick={() => {
            setFruit("apple");
          }}
        >
          Change to Apple
        </button>
        <button>Change to Banana</button>
      </div>
    </div>
  );
};

export default Example;

and when testing it out, we will be able to change the state fruit value from orange to apple.

Wonderful! now this means we were able to create a state, display it in our app, and change its value with user interaction. This is exactly the functionality that the useState hook provides.

to complete our example, we will create onClick handlers for all of our buttons.

import React, { useState } from "react";

const Example = () => {
  const [fruit, setFruit] = useState("orange");

  return (
    <div>
      <div>current value is: {fruit}</div>
      <div>
        <button
          onClick={() => {
            setFruit("orange");
          }}
        >
          Change to Orange
        </button>
        <button
          onClick={() => {
            setFruit("apple");
          }}
        >
          Change to Apple
        </button>
        <button
          onClick={() => {
            setFruit("banana");
          }}
        >
          Change to Banana
        </button>
      </div>
    </div>
  );
};

export default Example;

You can also check it in the codesandbox here:

Conclusion

These are the basics of the useState hook, and we barely scratched the surface of how we can use it. In the upcoming blog posts, we will dive more in-depth with it as well as have a look at the other react hooks, like useEffect!

Sing up to get an email notification when new content is published

Leave a Reply

Your email address will not be published. Required fields are marked *

Similar Posts