useState hook in React Building Blocks Jason Fleetwood-Boldt teaches code React JS

useState

So you probably want to know about useState in React 16.18 and if you do you’ve come to the right place.

I’m gonna break it all down for you, we’re gonna talk about useState, we’re gonna talk about hooks, we’re gonna talk about destructuring today so sit back and let’s dive in.

useState is a good place to start with understanding hooks.

Prerequesites for learning useState in React

PREREQUISITE KNOWLEDGE

this lesson relies on you understanding the following four basic concepts of ES6:

variables

Today we’ll just use a const.


What a ternary is — in this lesson I’ll use a ternary that is based on a variable called isActive.

If isActive is true, the ternary returns #E3A which is the hex color for PINK and if isActive is false the the ternary returns #FFF which is the hex color for white.

We’ll see what an arrow function is. A quick reminder that when an arrow function is passed a single value without curly braces, you don’t use the ‘return’ keyword.

When you do use the curly braces, remember to use the return keyword because Javascript will not explicily return from that function.

Finally, you’ll see at the top & bottom of our files the standard import-export.

Always remember to import the top-level modules you use as well as functions you want to use in your code.

In this case, we’ll just import React and useState from react

And then we’ll export at the bottom.

Here I’ve just written export default thing but in the real example I will export the name of the actual component.

Start with the default create-react-app.

Remove the default code in app.js and app.css

Create a new component as a stateless functional component. The component will be called toggleBox

import './App.css';

function App() {
  return (
    <>
    </>
  );
}

export default App;

So the next thing to do is define a ToggleBox

const ToggleBox = () => {

return (
<>

</>
)
}

export default ToggleBox

Remember alwasy to incldue export default.

From the stateless functional components, whatever is returned becomes the rendered content.

Test this in your browser and confirm thatyou see nothing and no error. You don’t see anything because you didn’t even put toggle box inside of the App yet. Let’s fix that:

import './App.css';
import ToggleBox from './toggleBox'

function App() {
return (
<ToggleBox />
);
}

export default App;

Be sure to import ToggleBox from './toggleBox' because we want to use it in this module.

Then also note that when referenced, the closing slash in <ToggleBox /> is not optional: That means the component is self-closing.

(The other way of doing this is <ToggleBox /></ToggleBox>

Now let’s focus on ToggleBox. I want to create a box that when I click, it will toggle on and when I click again it will toggle off.

We’ll manage this state locally in this functional component usin the useState hook.

Since ToggleBox was a functional component, we did not need React to be imported into toggleBox.js earlier.

Now we do, so add this to the top of toggleBox.js

import React, {useState} from 'react'

Inside of the return we want to render a div, and we’ll call it box by giving it a className, like so:

import React, {useState} from 'react'
const ToggleBox = () => {

  return (
    <>
      <div className={"box"}></div>
    </>
  )
}

export default ToggleBox

Now let’s add a state. The state is going to be called isActive.

import React, {useState} from 'react'

const ToggleBox = () => {
  const [isActive, setIsActive] = useState(false);
  return (
    <>
      <div className={"box"}></div>
    </>
  )
}

Here I’ve create two constants: isActive and setIsActive.

Both are destructured from the return value of useState(false);

In this case, false is the default value for our state (isActive). We pass the useState hook the default value of false.

Notice that here we are destructuring, or “pulling out of” the return value, isActive and setIsActive

We have now the state and also a way to set the state.

Next I want to display the background color of this box to be pink if it is active.

Then set the background color based on whether or not it is active.

ToggleBox implementation with useState Jason Fleetwood-Boldt codes React JS

Multiple States vs. One State

An alternative to calling useState many time is for a component’s state to be grouped together into a single, unified object. This has the advantage of forcing an update if the piece of information are closely related, but it has the downside of requiring you to update all parts of the combined object when you make a state update.

State Updates are Scheduled

One important catch is that all state updates are scheduled.

This only gets important when you want to update more than one state sequentially, and one state will depend on the updated value of another state

That means that when the interpreter gets to the line of code where you want the state to be updated, you can’t be guaranteed that the state variable itself hasn’t been updated.

In these cases, useState takes a functional call instead of an argument.