Sunday, August 1, 2021

React's useState hook

Let's test React's useState hook (please note these can only be used inside higher level functions and also, not inside conditionals)

import { array } from 'prop-types';
import React, { useState } from 'react';

function App3() {
  const useStateTest = useState("user");
  console.log(useStateTest);
  return (
    <h1>hello</h1>
  );
}

export default App3;

Console will print the following:

Array [ "user", dispatchAction() ]
0: "user"
1: function dispatchAction()
length: 2

As you can see in the array, this hook prints the "user" string in the first space followed by a function. This function is the one that lets you update the value of the first space within the array (kind of like a bridge).

Now, let's use an array deconstruct to just print the first item within the array to go next to our h1 element:

function App3() {
  const [useStateTest] = useState("user");

  return (
    <>
      <h1>hello {useStateTest}</h1>
    </>
  );
}

This time, your app will show the following in the browser:

hello user

Now let's change such string (or state variable) by making use of the useState hook in a button element:

First, we need to add our own custom name to the useState function (dispatchAction) which uses the second space within the array. By convention, the "set" prefix is always used here. So, we'll name it "setUserName" (please note that the variable within this function should not be limited to strings, it can also be numbers or booleans).

Next, we add the button into our app along with the onClick action handler which contains our custom setUserName useState function where we specify the new name to be displayed:

function App3() {
  const [useStateTest, setUserName] = useState("user");

  return (
    <h1>hello {useStateTest}</h1>
<button onClick={() => setUserName("Username")}>
Username
</button> ); }

Once you save, you'll see the same/previous heading + our new button

If you click the button, the string "user" will now change to "Username":

hello Username

..and that's it :)

No comments:

Post a Comment