useState behind the scences in react!!!

joedev090 - Oct 21 - - Dev Community

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

. . . . . . . .
Terabox Video Player