Logo

dev-resources.site

for different kinds of informations.

Hooks Behind The Scenes 2, useState!!

Published at
10/21/2024
Categories
react
usestate
frontend
hooks
Author
joedev090
Categories
4 categories in total
react
open
usestate
open
frontend
open
hooks
open
Author
9 person written this
joedev090
open
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

hooks Article's
30 articles in total
Favicon
Hooks Behind The Scenes 3, UseRef!!!
Favicon
A Complete Guide to All React Hooks for Beginners
Favicon
Using useReducer for Complex State Logic
Favicon
Descobrindo o useCallback do React
Favicon
Discovering React’s useCallback
Favicon
Mastering Code Quality in Laravel: Pint with Git Hooks and Docker
Favicon
React: leveraging custom hooks to extract reusable logic
Favicon
Hooks Behind The Scenes 2, useState!!
Favicon
Mastering React Functional Components: Hooks, useEffect, and Lifecycle Explained
Favicon
JSHooks API compare to CHooks
Favicon
The Ultimate Guide to Wall Hanging Hooks and Display Systems for Your Home and Office
Favicon
How to Detect if an Element is in View with React
Favicon
React useQuery : A Complete Guide
Favicon
{useState} HooK { Briefly Explained};
Favicon
React HooK= { Briefly Explained};
Favicon
What is useState?
Favicon
Actions - React 19
Favicon
React controlled and uncontrolled hooks
Favicon
React Concepts: Hook Proximity
Favicon
Demystifying React's useState Hook: A Comprehensive Guide
Favicon
Mastering React Hooks: Best Practices for Efficient and Maintainable Code
Favicon
Designing React Hooks for Flexibility
Favicon
Unleashing the Power of React Custom Hooks
Favicon
Understanding Context Hooks in React: A Beginner's Guide
Favicon
3 Ways To Create Engaging React Loading Screens with Hooks
Favicon
Understanding the useInteractionTimer Hook: Measuring Component Interaction Time in React
Favicon
Cats Fatc's Quick project
Favicon
All About Custom Hooks: Supercharge Your React Components
Favicon
Suggestion for new syntax of React reducers + context
Favicon
How To Define Typescript onChange Event In React

Featured ones: