React useState's usage

React useState's usage

Hello everyvone, I will tell you useState hook's using on the React. React creates user interface design so, a lot of subject also helpful developer. Our website visited users, useState users' catch interaction and it will be render components again. In addition to this what is Components? On our website cerated all React elements are a component.

For example, create a component; in the field I have selected or called, the component will write "Hello World!"

const textVisible = () => {
   return <p>Hello World!</p>
}        

Okay, let's understand the general work logic of Components and useState and see the syntax of useState. First, start with importing the useState hook.

import { useState } from 'react';        

In addition to this, create a component that takes an empty parameter.

import React, { useState } from 'react';

export default function App() {
  return (
    <div>
      <h1>Hello World!</h1>
    </div>
  );
}        

And now, firstly create the useState hook and the useState hook takes the following parameters:

  • initialState: the value you want the state to be initially. It can be a value of any type, but there is a special behaviour for functions. This argument is ignored after the initial render.
  • state: Variable changed by setState function. setState function on called, specified text with state variable value's changed.
  • setState: state variable update transaction providing function.

const [state, setState] = useState(initialState);        

Let's using useState hook and For example;

  • Create a button and parargraphs (<p>),
  • Every time button clicked state variable's value one increase.
  • useState hook's will first value "0"

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

export default function App() {
  const [number, setNumber] = useState(0);

  return (
    <div className="App">
      <p>{number}</p>
      <button onClick={() => setNumber(number + 1)}>Increase</button>
    </div>
  );
}        

However look at writed code, created a button and "<p>" label with text and every button clicked time state variable's value one increase code working but "<button>" label in use a problem exist,

On click number via variable one increase and that isn't good practices. Instead of this that "setNumber" function let's change like the following.

<button onClick={() => setNumber((p) => p + 1}>Increase</button>        

With that code, the value of the number variable increases by one and it becomes suitable for use.

Now, let's create a difficult example;

  • Create an HTML form that includes two input fields and a button.
  • The input values should be filled in correctly, and when the button is clicked, the "users" variable will be updated.
  • The "users" variable will also update when a new user is added, including the end users.

And now, let's proceed with step-by-step code writing.

  • Firstly, let's create useState hooks and assign the initial value.

  const [users, setUsers] = useState([]);
  const [name, setName] = useState("");
  const [lastName, setLastName] = useState("");         

  • Let's create a HTML form that includes two input fields and a button.

<form onSubmit={(e) => handleSubmit(e)}>
        <input
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Entry name"
        />
        <input
          value={lastName}
          onChange={(e) => setLastName(e.target.value)}
          placeholder="Entry surname"
        />
        <button>Add a new user</button>
</form>        

Okay, now created code in different structure available and let's analysing code.

  • "input" labels "name" and "lastname" variables' values shows and stores.
  • "form" label "onSubmit" with send and "handleSubmit" function will start.

const handleSubmit = (e) => {
    e.preventDefault();

    if (name && lastName) {
      setUsers([...users, { id: crypto.randomUUID(), name, lastName }]);
      setName("");
      setLastName("");
    } else if (!name || !lastName) {
      alert("Form has empty values!");
    }
  };        

"handleSubmit" function details;

  • Entry made name and surname information's control to ensure ve useState hook's change value.
  • Finally, "users" makes state value assignment.

At last, updated users list values with over selected HTML elements will add.

{users.length > 0 ? (
        users.map((item) => {
          return <p key={item.id}>{`${item.name} ${item.lastName}`}</p>;
        })
      ) : (
        <p>Users list are empty</p>
)}        
Article content

With this article React useState hook's use to tell tried me and React over official document detailed information can take.

Thank you for recommending our website! Your support means a lot to us! 💚

To view or add a comment, sign in

More articles by Enes Akkaya

  • Derin Öğrenme DeepFace Uygulaması

    Merhaba, ML Öğrenmesinin alt dalı olan Derin Öğrenmeye giriş yapabileceğimiz yüz tanıma ile ilgili bir yazı hazırlamak…

  • Python ile Web Tabanlı Veri Görselleştirme

    Merhaba, bu yazı içerisinde Python ile interaktif şekilde kullanabileceğiniz ve Web tabanlı verilerinizi analiz…

  • React Todo Project with JSON Server

    Hello everyone, In this article will create a todo project via React and JSON Server. We will development REST API with…

  • Streamlit Uygulama Geliştirme

    Merhaba, bu yazı içerisinde Streamlit ile proje geliştirmeyi, prototip hazırlama ve dinamik yapılar nasıl…

  • JavaScript ile Veri Analizi

    Merhaba, Python üzerinde Pandas kütüphanesi kullanarak; veri analizi, veri manipülasyonu gibi yapılar oluşturabiliyoruz…

  • Read Excel data and visualize with React

    Hello everyone, I will tell you Excel data read and fetched data visualization in this article. We will use xlsx and…

  • Typescript Değişkenler

    Merhaba, bu yazı içerisinde JavaScript'in bir üst kümesi olarak diyebileceğimiz TypeScript üzerinde değişken…

  • React Web Scraping

    Merhaba, bu yazı içerisinde genel olarak birden fazla yazılım dilleri üzerinde kullanan "Web Scraping" olarak geçen ve…

  • React Context API

    Merhaba, bu yazı içerisinde Context API konusu hakkında başlangıç ve bilgilendirici nitelikte bir yazı hazırlamaya…

  • React useReducer

    Merhaba bu yazı içersinde React içerisinde daha önceden yazı olarak oluşturduğum; useState yapısının alternatifi olarak…

Others also viewed

Explore content categories