DEV Community

bappasaha
bappasaha

Posted on

Hooks001: Use State Hook

2.0 React Hooks:

👍Github Code:

📚Article To Read Link
⭐ Simple CRUD Using useState Hook

  • React hooks are introduced in 2019 in react version 16.8_+
  • Hooks can not be used inside class component.

What hooks solved?

  • State
  • Life Cycle Method
  • Duplicate Code
  • Sharing Same Logic

Hook Rules

  • Hook is used in top level.

useState hook

const [todo,setTodo]=useState()
Enter fullscreen mode Exit fullscreen mode
  • āĻāĻ–āĻžāύ⧇, āĻĒā§āϰāĻĨāĻŽ āχāύāĻĄā§‡āĻ•ā§āϏ⧇ āĻĨāĻžāĻ•āĻŦ⧇ āϭ⧇āϰāĻŋāϝāĻŧ⧇āĻŦāϞ (todo) āĻāĻŦāĻ‚ āĻĻā§āĻŦāĻŋāϤ⧀āϝāĻŧ āχāύāĻĄā§‡āĻ•ā§āϏ⧇ āĻĨāĻžāĻ•āĻŦ⧇ āĻĢāĻžāĻ‚āĻļāύ (setTodo)

  • This hook return an array.

āφāĻŽāϰāĻž āĻāĻ•āϟāĻŋ āĻ…ā§āϝāĻžāϰ⧇ āĻĨ⧇āϕ⧇ āĻŽāĻžāύ āϗ⧁āϞāĻŋ āύāĻŋāϤ⧇ āϚāĻžāχāĻŦ, āĻāĻŦāĻ‚ āφāĻŽāĻžāĻĻ⧇āϰ āĻ…ā§āϝāĻžāϰ⧇ āĻĄāĻŋāĻ¸ā§āĻŸā§āϰāĻžāĻ•āϚāĻžāϰāĻŋāĻ‚ āĻ•āϰāϤ⧇ āĻšāĻŦ⧇ that is āĻ…āĻŦāĻœā§‡āĻ•ā§āϟ āĻĄāĻŋāĻ¸ā§āĻŸā§āϰāĻžāĻ•āϚāĻžāϰāĻŋāĻ‚ āĻ•āϰāĻžāϰ āĻŽāϤāĨ¤

āĻ…āĻŦāĻœā§‡āĻ•ā§āϟ āĻĄāĻŋāĻ¸ā§āĻŸā§āϰāĻžāĻ•āϚāĻžāϰāĻŋāĻ‚:


 const  state={
        todo:' ',
        warning:null
    }
 const {todo,warning}=state
Enter fullscreen mode Exit fullscreen mode

Array āĻĄāĻŋāĻ¸ā§āĻŸā§āϰāĻžāĻ•āϚāĻžāϰāĻŋāĻ‚:

const array=[‘bappa’,’appa’,’totot’];
const [a,b,c]=array; // a=’bappa’ consol log 

Enter fullscreen mode Exit fullscreen mode

✅ Example:1 where useState take object as argument

  const [todo, setTodo] = useState({
    title: " ",
    description: " ",
  });
Enter fullscreen mode Exit fullscreen mode

Solution code is

import React from "react";
import { useState } from "react";

export default function Example1Todo() {
  const [todo, setTodo] = useState({
    title: " ",
    description: " ",
  });

//   const handleChangeInput = (e) => {};

  const { title, description } = todo;
  return (
    <div>
      <hr />
      <h4>Example1 too</h4>
      <p style={{ backgroundColor: "yellow" }}>Title:{title}</p>
      <br />
      <input
        type="text"
        value={title}
        onChange={(e) =>
          setTodo({
            ...todo,
            title: e.target.value,
          })
        }
      />
      <br />
      <br />
      <textarea
        placeholder="enter your text"
        name="text"
        value={description}
        onChange={(e) =>
          setTodo({
            ...todo,
            description: e.target.value,
          })
        }
      />
      <hr />
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Refactor of the code is

import React, { useState } from "react";

export default function Example1Todo() {
  const [todo, setTodo] = useState({
    title: "",
    description: "",
  });

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setTodo({
      ...todo,
      [name]: value, // this will dynamically update value
    });
  };

  const { title, description } = todo;

  return (
    <div>
      <hr />
      <h4>Example1 Todo</h4>
      <p style={{ backgroundColor: "yellow" }}>Title: {title}</p>
      <br />
      <input
        type="text"
        name="title"
        value={title}
        onChange={handleInputChange}
      />
      <br />
      <br />
      <textarea
        placeholder="Enter your text"
        name="description"
        value={description}
        onChange={handleInputChange}
      />
      <hr />
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Example:2 where useState take previous value as argument

  const [todo, setTodo] = useState(0);
Enter fullscreen mode Exit fullscreen mode

This is not the good practice

import React, { useState } from 'react'

function Counter() {

    const [count, setCount]=useState(0)
    return (
        <div>
            {count}
            <p>
                <button

                type='button'
                onClick={()=>setCount(count+1)}
                >
                    Add 1
                </button>
            </p>
        </div>
    )
}

export default Counter
Enter fullscreen mode Exit fullscreen mode

This is the good practice

<button

    type='button'
    onClick={()=>setCount((prevState)=>prevState+1)}
    >
    Add 1
    </button>

// good practice

    // let j =0;
    // const addTen=()=>{
    //     while(j<10){
    //         setCount(
    //             (prevState)=>prevState+1
    //         );
    //         j++;
    //     }
    // }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)