DEV Community

joedev090
joedev090

Posted on • Edited on

1

Hooks Behind The Scenes 2, useState!!

Hey Coders!!

One of the most important hook in react is the useState.

useState hook is used to access state in React functional components. A special function that allows you to manage state within functional components without the need for class-based components.

The useState provides a way to declare and manage state variables directly within a function component with useState keyword and can only be used to declare one state variable.

useState(0)

With a little introduction, let's see Code!!
It is better, after that I will explain it.

import {useState} from "react";

export default function App() {
    const array = useState(0);
    const counter = array[0];
    const setCounter = array[1];
    console.log(array);

    function increaseCounter() {
        setCounter(counter + 1);        
    }

    return (
        <>
           <h1>Counter: { counter }</h1>   
            <button onClick={increaseCounter}>Increase</button>
        </>
  )
}
Enter fullscreen mode Exit fullscreen mode

This is a basic example of a counter in React using the useState hook.

Explanation:

  1. Using and updating state with useState()

useState(0): We initialize the state counter with an initial value of 0. The useState hook returns an array with two elements: the current state value and a function to update that value.

array[0]: The first element of the array returned by useState is the current state value (counter).

array[1]: The second element of the array is the function to update the state (setCounter).

function increaseCounter(): We define a function increaseCounter that will be executed when the button is clicked.

setCounter(counter + 1): We use the setCounter function to update the state counter by incrementing it by 1.

Finally we can remove these three lines:

const array = useState(0);
const counter = array[0];
const setCounter = array[1];
Enter fullscreen mode Exit fullscreen mode

Instead of this to have a more clear code and most developers use:

Full clean code again:

Note: We are using destructuring in javascript!!

import {useState} from "react";

export default function App() {
    const [counter, setCounter] = useState(0);

    function increaseCounter() {
        setCounter(counter + 1);        
    }

    return (
        <>
           <h1>Counter: { counter }</h1>   
            <button onClick={increaseCounter}>Increase</button>
        </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Here we have a basic code where we are showing how to use useState.

Also we can check how to use more than one useState and then redefine the useState with an object.

Lets check

import {useState} from "react";

export default function App() {
    const [counter, setCounter] = useState(0);
    const [name, setName] = useState("Joe");

    function increaseCounter() {
        setCounter(counter + 1);        
    }

    return (
        <>
           <input type="text" 
               onChange={(e) => setName(e.target.value)} 
               value={name}
            />
            <h1>Name: {name} Counter: { counter }</h1>   
            <button onClick={increaseCounter}>Increase</button>
        </>
  )
}
Enter fullscreen mode Exit fullscreen mode

We created two useStates for counter and name.

But we can improve it, using only one useState and set an object where we have the two vars:

import {useState} from "react";

export default function App() {
    const [details, setDetails] = useState({ counter: 0, name: "" })

    function increaseCounter() {
        setDetails( (prev) => ({
            ...prev,
            counter: prev.counter + 1,
        }));        
    }

    function onChangeInput(value ) {
        setDetails( (prev) => ({
            ...prev,
            name: value,
        }));    
    }

    return (
        <>
           <input type="text" 
               onChange={ (e) => onChangeInput(e.target.value ) } 
               value={details.name}
            />
            <h1>Name: { details.name } Counter: { details.counter }</h1>   
            <button onClick={increaseCounter}>Increase</button>
        </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Finally we can see how to use useState in a better way and more productive.

If you have any questions, don't hesitate in comment the post.

Please see the reference below to see useState in more details:

https://react.dev/reference/react/useState

Top comments (0)

Agent.ai Challenge image

Congrats to the Agent.ai Challenge Winners 🏆

The wait is over! We are excited to announce the winners of the Agent.ai Challenge.

From meal planners to fundraising automators to comprehensive stock analysts, our team of judges hung out with a lot of agents and had a lot to deliberate over. There were so many creative and innovative submissions, it is always so difficult to select our winners.

Read more →

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay