0% found this document useful (0 votes)
6 views3 pages

Document_useState

Uploaded by

go.coronago
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Document_useState

Uploaded by

go.coronago
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 3

useState Hook:

1. What is it?

useState is a React Hook that lets you add a state variable to your component.

Syntax: const [state, setState] = useState(initialState);

state is a state variable and setState is a function that updates the state value.

2. What is the real time scenario for this hook ?

In order to make use state variables in our React Component we can make use of useState hook.

For example:

Storing form data and displaying it.


import { useState } from 'react';

export default function Form() {

const [name, setName] = useState('Taylor');

const [age, setAge] = useState(42);

return (

<>

<input

value={name}

onChange={e => setName(e.target.value)}

/>

<button onClick={() => setAge(age + 1)}>

Increment age

</button>

<p>Hello, {name}. You are {age}.</p>

</>
);

3. What benefit we get from it.

Creating state variables to store some data and also passing that data to other components.

4. When do I use it?

If we want to store some data within our component , we can make use of useState to declare a state
variable to store that data into it.That data could be passed to other component via props as well.

5. How to use it??

import { useState } from "react";

import ReactDOM from "react-dom/client";

function FavoriteColor() {

const [color, setColor] = useState("red");

return (

<>

<h1>My favorite color is {color}!</h1>

<button

type="button"

onClick={() => setColor("blue")}

>Blue</button>

</>

Output:
Initial Render:

On Button Click:

You might also like