Welcome to our blog!

Understanding React’s useState Hook

Posted by:

|

On:

|

Image from Canva Pro

To use buttons, you can add the onClick event handler to handle clicks on the button.

React also follows the camelCase unlike HTML/JavaScript; and to run the JavaScript, you add an embedded expression.

App.jsx

import React from "react";
const App = () => {
const handleClick = () =>
console.log("Hi");
};
return (
<div>
<h1>Click the button</h1>
<button onClick = { handleClick } >Click me</button>
</div>
);
};

export default App;

You can also run JavaScript directly inside the embedded expression. However, it is executed without clicking the button because the function is called immediately instead of being passed as an event handler.

App.jsx

import React from "react";

const App = () => {
return (
<div>
<h1>Click the button</h1>
<button onClick = { console.log("Hi") }>Click me</button>
</div>
);
};

export default App;

This is not what we usually want. Thus, to avoid this, we wrap the code in an arrow function. The arrow function won’t run immediately. It waits until the even triggers it.

App.jsx

import React from "react";

const App = () => {
return (
<div>
<h1>Click the button</h1>
<button onClick={ () => console.log("Hi")}>Click me</button>
</div>
);
};

export default App;

State is a special way in React to make components remember values.

To render JavaScript, we need an embedded expression.

App.jsx

import React from "react";

const App = () => {
const handleClick = () => {
console.log("Button clicked");
};

return (
<div>
<h1>Click the button</h1>
<p>You clicked the button { 0 } time(s).</p>
<button onClick={handleClick}>Click me</button>
</div>
);
};

State is used to make React components remember values between renders. E.g. tracking how many times a button has been clicked.

To do this, we first import useState from the “react” package. As this is a named export, we use {} to specify which part we went to import.

App.jsx

import React, { useState } from "react";

const App = () => {
let count = 0;

const handleClick = () => {
console.log("Button clicked");
};

return (
<div>
<h1>Click the button</h1>
<p>You clicked the button {0} time(s).</p>
<button onClick={handleClick}>Click me</button>
</div>
);
};

export default App;

To define State, we use an array structure and put the name of the variable we want to use inside the array.

Next, we would assign a value with the useState function. useState is a special function (called a hook) in React that allows components to remember and update values over time.

To do this, we pass the initial value we want to set as an argument to the useState function.

With the example below, we use the setCount function to update the count variable automatically when we call the function and pass a new value as the argument. Whenever setCount is called, the count variable is updated and re-rendered.

In this example, the function is called the setter function.

App.jsx

import React, { useState } from "react";

const App = () => {
const [ count, setCount ] = useState(0);

const handleClick = () => {
console.log("Button clicked");
setCount (count + 1);
};

return (
<div>
<h1>Click the button</h1>
<p>You clicked the button { count } time(s).</p>
<button onClick={handleClick}>Click me</button>
</div>
);
};

export default App;

Therefore, useState hook allows React component to remember values across renders.

When you’re using React, you aren’t limited to one state variable. You can have as many as you want! You can also decide the initial value. It can be anything you want.

Did you know that you aren’t limited to numbers when it comes to state variables?

App.jsx

import React, { useState } from "react";

const App = () => {
const [happiness, setHappiness] =
useState ( "😊" );

const addSmile = () => {
setHappiness(happiness + "😊");
};

return (
<div>
<h1>Happiness Generator</h1>
<p>{happiness}</p>
<button onClick={addSmile}>Add a Smile</button>
</div>
);
};

export default App;

Booleans (i.e. True and False) can also be used for state variable.

App.jsx

import React, { useState } from "react";

const App = () => {
const [isLightOn, setIsLightOn] = useState(false);

const toggleLight = () => {
setIsLightOn(!isLightOn);
};

return (
<div>
<h1>Light Switch</h1>
<p>Is the light on? {String(isLightOn)}</p>
<button onClick={toggleLight}>Toggle Light</button>
</div>
);
};

export default App;

You can also use a non-state variable and render it. However, when we update a variable that’s also rendered, React won’t update the HTML it displays.

For example, count is a regular variable and not a state. Therefore, React won’t re-render when count changes.

App.jsx

import React from "react";

const App = () => {
let count = 0;

const handleClick = () => { count +=1 ;
console.log(count);
};

return (
<div>
<h1>Click the button</h1>
<p>You clicked the button {count} time(s).</p>
<button onClick={handleClick}>Click me</button>
</div>
);
};

export default App;

For React to render the updated HTML, you need to use the setter for the state variable.

Note: Never update a state variable directly, but only through the setter.

index.html

<html>
<head>
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="root">loading</div>
</body>
</html>

index.jsx

import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(<App />);

App.jsx

import React, { useState } from "react";

const App = () => {
const [count, setCount] = useState(0);

const handleClick = () => {
console.log("Button clicked");
setCount(count + 1);
console.log(count);
};

return (
<div>
<h1>Click the button</h1>
<p>You clicked the button {count} time(s).</p>
<button onClick={handleClick}>Click me</button>
</div>
);
};

export default App;

When you call the setter function, React schedules the update but it doesn’t apply it immediately since State updates are asynchronous.

If we use the updated state value right after calling the setter, it may still reflect the previous value.

Therefore, remember that hooks, such as useState, run asynchronously. We can’t know when the variable is updated and the HTML is re-rendered.

  • useState hook: is what we use to ensure that React updates the HTML when a state variable changes. It’s primary purpose is to manage state in components
  • State updates are asynchronous
  • We reference a variable defined in JavaScript inside a JSX tag by using curly braces {}
  • Quick example of a state variable declaration using useState: const [ count, setCount ] = useState(0);
  • Correct syntax to add a click event handler to a button in React: onClick = { handleFunction }
  • Why is it necessary to use a closing slash for self-closing tags that don’t require it in plain HTML: JSX syntax rules require it
  • Quick example of the correct way to use multiple props to pass values: <Character name=“Mickey” costume=“Sorcerer” />
  • Why does updating a regular variable in React re-render the page: React doesn’t track the changes of regular variables
  • Boolean is the property type that cannot be directly rendered in React without conversion
  • Quick example of the function that will correctly log “You clicked me!”: const showMessage = () => console.log(“You clicked me!”);
  • Quick example of implementing the state variable counter for coffee orders:

CoffeeOrder.jsx

import React, { useState } from "react";

const CoffeeOrder = () => {

const [ coffees, setCoffees ] = useState (0);
const addCoffee = () => {
setCoffees(coffees + 1);
};

return (
<div>
<h2>Coffee Orders</h2>
<p>You've got {coffees} coffee(s) ordered.</p>
<button onClick={addCoffee}>Order Coffee</button>
</div>
);
};

export default CoffeeOrder;
  • Quick example of calling setVotes inline and wrapping it in an arrow function to ensure it gets called with the button click:

Votes.jsx

import React, { useState } from "react";

const Votes = () => {
const [votes, setVotes] = useState(0);

return (
<div>
<p>Number of votes: {votes}</p>
<button onClick={ () => setVotes(votes + 1) }>Add Vote</button>
</div>
);
};

export default Votes;
  • Quick example of updating the character and the clothes correctly:

index.html

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="./index.css" />
<style>
h3 {
margin-bottom: 0px;
}

p {
margin-top: 4px;
}
</style>
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>

index.jsx

import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(<App />);

App.jsx

import React, { useState } from "react";

const App = () => {
const [ character, setCharacter] = useState("Plumber");
const [clothes, setClothes] = useState("Overalls");

const toggleCharacter = () => { setCharacter ((prevCharacter) => (prevCharacter === "Plumber" ? "Gorilla" : "Plumber"));
};
const toggleClothes = () => { setClothes ((prevClothes) => (prevClothes === "Overalls" ? "Shorts" : "Overalls"));
};

return (
<div>
<h1>Create your Character</h1>
<h2>Your current character is:</h2>
<h3>{character}</h3>
<p>
in <strong>{clothes}</strong>
</p>
<button onClick={toggleCharacter}>Switch Character</button>
<button onClick={toggleClothes}>Switch Clothes</button>
</div>
);
};

export default App;

  • Implementing Dark Mode in React

    We have previously talked about useState before. A great way to create CSS classes on the fly is to use state variable! Here is an example of how to create Dark Mode in React by using string interpolation to construct the individual classes based on the state variable mode. index.html index.jsx App.jsx App.css So, if…

  • Understanding React’s useState Hook

    Buttons To use buttons, you can add the onClick event handler to handle clicks on the button. React also follows the camelCase unlike HTML/JavaScript; and to run the JavaScript, you add an embedded expression. App.jsx You can also run JavaScript directly inside the embedded expression. However, it is executed without clicking the button because the function is…

  • Understanding Props in React: A Comprehensive Guide

    This content explains the concept of props in React, which allow data to be passed to components, making them dynamic. It covers how to access props as objects, pass multiple properties, and handle different data types. The importance of correctly rendering non-string values and using props in JSX is emphasized.

  • The Power of JSX: Combining HTML and JavaScript

    JSX is a syntax extension for JavaScript that resembles HTML, used primarily in React to create components. It allows developers to write HTML-like code within JavaScript, enhancing readability and enabling dynamic web applications. With JSX, one can embed JavaScript expressions, making the integration of logic and UI layout seamless.

  • Organizing React Components for Better Code

    The content discusses best practices for organizing React components in separate files for maintainability. It details the process of importing React, creating functional components, and exporting them. Additionally, it covers returning multiple elements and using named vs. default exports, emphasizing strategic organization for better code management.

  • Step-by-Step Guide to Rendering React Components

    The content provides a step-by-step guide on rendering components in React. It emphasizes creating and linking HTML and JavaScript files, setting up the main component, and utilizing the createRoot function to manage rendering. The author injects humor while guiding readers through the essential concepts of React component rendering.

  • Introduction to React: Understanding the Basics

    React is a JavaScript library for creating single-page web applications that dynamically update without page reloads. It organizes code into reusable components, akin to functions returning HTML-like JSX. This enhances development efficiency, as components can be reused, resembling custom HTML tags. Overall, React simplifies coding while improving functionality.

  • HTML Structure Explained: A Beginner’s Guide

    The content discusses HTML, the foundational markup language for web development. It highlights its structure, including elements like tags and attributes. The post humorously reflects on the author’s learning journey while encouraging newbies by simplifying concepts like nesting elements and the importance of HTML in web design. It concludes with code examples.

  • Why Use Pure Functions in React Components?

    Pure functions in JavaScript are self-contained and produce consistent results without affecting external variables or objects. They enhance clarity and maintainability in code, minimizing bugs. Unlike impure components that modify existing variables, pure components receive data as props. Understanding component relationships, like the React render tree and module dependency tree, further optimizes performance and structure.

  • React Components Explained: A Guide for Developers

    This post analyzes React components, highlighting their crucial role in creating dynamic user interfaces. It details the types of components, including functional and class components, and explains props and state. Additionally, it covers lifecycle methods and emphasizes the importance of reusability and composition in building complex applications effectively.



Discover more from Steal My Notes

Subscribe to get the latest posts sent to your email.

Posted by

in

Discover more from Steal My Notes

Subscribe now to keep reading and get access to the full archive.

Continue reading