DEV Community

VINOTH
VINOTH

Posted on

React useState Hook - Day1

1) Toggle Button:
You build a button that switches between:
"ON" ↔ "OFF"
What type of state should you use?
What is the best initial value?

import { useState } from "react"

function Toggle() {

  const [status, setStatus] = useState("OFF");

    function togglebtn() {

            if (status === "OFF") {
                setStatus("ON");
            }else{
                setStatus("OFF");
            }
    }

    return(
        <div>
            <h1>{status}</h1>
            <button onClick={togglebtn}>Toggle</button>
        </div>
    )
}

export default Toggle

Enter fullscreen mode Exit fullscreen mode

2) Input Field Value:
You have a text input.
User types name and you want to display:
Hello, Vinoth
Why must the input value be stored in useState?
What happens if you use a normal variable?

import { useState } from "react"

function Name() {

    const [name, setName] = useState("");

    function handle(e) {

        setName(e.target.value);

    }

    return(
        <div>
            <input 

                 value={name}
                 onChange={handle}
            />
            <h1>Hello, {name}</h1>
        </div>
    )
}

export default Name
Enter fullscreen mode Exit fullscreen mode

3) Show/Hide Text:
You want to show paragraph only when button is clicked.
What kind of state works best?
Why boolean is suitable here?

import { useState } from "react"

function Text() {

  const [show, setShow]= useState(false);

    function handle () {

        if (show === false) {
            setShow(true)
        }else{
            setShow(false)
        }

    }

    return(
        <div>
           <button onClick={handle}>
            show / hide
           </button>

           {show && <p>Hello! This is my paragraph.</p>}
        </div>
    )
}

export default Text

Enter fullscreen mode Exit fullscreen mode

4) Character Counter:
User types in textarea. You show number of characters.
How do you track text length?
Should you store both text and length in state?

import { useState } from "react"

function Count() {

  const [text, setText]= useState("");



    return(
        <div>
          <textarea 

          value={text}
          onChange={(e)=>setText(e.target.value)}

          />

          <p>Characters: {text.length}</p>
        </div>
    )
}

export default Count
Enter fullscreen mode Exit fullscreen mode

Top comments (0)