Let's React on useState( )

Let's React on useState( )

useState( ) guide for beginner

I won’t lie it took 4 days to me understand useState hook thoroughly. So let’s dive deep into and learn from basics.

Let’s go to our good old GOAT 🐐 friend Javascript

export default function App() {
    let state = "No" 
        state= " Damn No! "

    return (
        <main>
            <h1 className="title">Do you know useState()?</h1>
            <button className="value">{state}</button>
        </main>
    )
}

Here I declared a state variable (using let keyword - if you have WHY 🤨 then I highly recommended to go back to Javascript and learn let v/c const 🙇🏽) and changing it’s value to “Damn No”

So output will be something like this :

Now you will be like this is not rocket-science 🚀 I agree but now let’s do some magic🪄

I just want to change variable value onClick event. Still think in Javascript. Simple right ? Just add onClick event listener and call a function on that button’s click event.export default function App() {

 export default function App() {

    let state = "No";

  function handleClick() {
    state = " Damn No! ";
    console.log("funcion called!"); // checking function is called or not !
  }

  return (
    <main>
      <h1 className="title">Do you know useState()?</h1>
      <button className="value" onClick={handleClick}>
        {state}
      </button>
    </main>
  );
}

Surprisingly function called but value is not changing on the UI 🧐

1. Rule of Thumb 👍🏽 : Simply changing value of your state variable won’t make React to React 😆. It won’t trigger react to re-run / re-render component.

So, we have to use React’s provided method. ( React is the boss!)

Here comes useState( ) function (I’m keeping it simple as “hook” terms scared 😰 me)

It’s given by React so we import it from “react”

import { useState } from "react"

Now why we used { } ← because it’s a named import. Now what’s that ? 🤔

if you go to /node_modules/react/cjs/react.development.js you will find many exports!

 exports.useState = function (initialState) {
      return resolveDispatcher().useState(initialState);
    }; // this is your useState( ) functionality

Don’t think much this file has more than one export that’s why we use { } named import !

Now back to basic…..


import { useState } from "react";

export default function App() {

  const result = useState();

  console.log(result); // it will return an array with 2 values
return (
    <main>
      <h1 className="title">Do you know useState()?</h1>
      <button className="value">

      </button>
    </main>
  );

}

at index [0] it’s returning : undefined and at index [1] : it’s returning some function f()

2. Rule of Thumb 👍🏽 : useState( ) will return an array

Now, let us play with some code by adding argument to useState function :

import { useState } from "react";

export default function App() {
  const result = useState("Hello", "Bro", 0, 1);

  console.log(result);

  let state = "No";

  function handleClick() {
    state = " Damn No! ";
    console.log("funcion called!");
  }

  return (
    <main>
      <h1 className="title">Do you know useState()?</h1>
      <button className="value" onClick={handleClick}>
        {state}
      </button>
    </main>
  );
}

so it’s initializing only one value as an array index[0]. Cool we learned that how to apply initial state : useState(initialState)

Now you rush like me and do this :

import "./styles.css";
import { useState } from "react";

export default function App() {
  const result = useState("Hello");

  console.log(result);

  return (
    <main>
      <h1 className="title">Do you know useState()?</h1>
      <button className="value">{result[0]}</button>
    </main>
  );
}

You are confident you learn useState and now I tell you to change value of result.
You will promptly change result to let and update it’s value

import { useState } from "react";

export default function App() {
  let result = useState("Hello");
  function handleClick() {
    result = "bro";
    console.log("clicked!");
  }
  console.log(result);

  return (
    <main>
      <h1 className="title">Do you know useState()?</h1>
      <button className="value" onClick={handleClick}>
        {result[0]}
      </button>
    </main>
  );
}

Because you forgot my #1. Rule of Thumb 👍🏽 : Simply changing value of your state variable won’t make React to React 😆. It won’t trigger react to re-run / re-render component.

I know you are pulling your hair and thinking to leave this blog but wait :

Remember useState( ) return 2 items array : let’s destructure an array

 const [result, setResult] = useState("Hello"); 
// first is your state variable result
// second is your function which will you use to modify value of your state variable 

// You can call anything to that setResult function : 

 const [result, whateverIwant] = useState("Hello"); // but using common convention makes a better developer

We have done array destructuring so we can use {result} instead of {result[0]}
Now again you are in rush and you did something :

import { useState } from "react";

export default function App() {
  const [result, setResult] = useState("Yes");

  return (
    <main>
      <h1 className="title">Is state important to know?</h1>
      <button className="value">{setResult(result)}</button>
    </main>
  );
}

You are upset ! ☹️ Again go to #1. Rule of Thumb 👍🏽 : Simply changing value of your state variable won’t make React to React 😆. It won’t trigger react to re-run / re-render component. Think this in reverse ! You changed state variable and it re-rendering the component (here in infinite loop.) because you have to change state on user interaction.

import { useState } from "react";

export default function App() {
  const [result, setResult] = useState("Yes");

  function handleClick() {
    setResult("Heck yes");
  }
  return (
    <main>
      <h1 className="title">Is state important to know?</h1>
      <button className="value" onClick={handleClick}>
        {result}
      </button>
    </main>
  );
}

3. Rule of Thumb 👍🏽 : useState( ) is necessary when you have to change the value of your state variable on user interaction

🎉🎉You Did it 🎉🎉

We will learn more useState( ) in next blog. Stay Tuned……