0% found this document useful (0 votes)
10 views6 pages

Day - 11 State Management With Usestate

The document explains the useState hook in React, which allows functional components to manage state. It provides syntax, examples, and practical applications, including counter, toggle, text input, and multiple states in a component. useState triggers re-renders when the state changes, enhancing interactivity in React applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Day - 11 State Management With Usestate

The document explains the useState hook in React, which allows functional components to manage state. It provides syntax, examples, and practical applications, including counter, toggle, text input, and multiple states in a component. useState triggers re-renders when the state changes, enhancing interactivity in React applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

State Management with useState

1. What is useState?

In React, state refers to data that can change over time and affects how the component renders.
React allows functional components to have state by using the useState hook. Before React
introduced hooks, only class components could have state, but useState allows functional
components to have state as well.

useState is a hook that allows you to:

 Declare state variables inside a functional component.

 Update state and re-render the component when the state changes.

Syntax of useState:

const [state, setState] = useState(initialValue);

 state: A variable that holds the current value of the state.

 setState: A function used to update the state. When called, it will trigger a re-render of the
component.

 initialValue: The value with which the state is initialized when the component first renders.

Example of useState:

import React, { useState } from 'react';

function App() {

const [counter, setCounter] = useState(0); // state initialized to 0

const increment = () => setCounter(counter + 1); // Function to update state

return (

<div>

<p>Counter: {counter}</p>

<button onClick={increment}>Increase</button>

</div>

);

}
export default App;

Explanation:

1. const [counter, setCounter] = useState(0);

o This line declares a state variable called counter and a function setCounter to update
it. Initially, counter is set to 0.

2. increment is a function that calls setCounter, updating the value of counter to counter + 1.

3. When you click the button, it triggers the increment function, which updates the state. React
automatically re-renders the component, reflecting the updated counter value.

2. Practical Example: Counter Component

Let's expand on the counter example. The counter will display the number of times a button has
been clicked.

import React, { useState } from 'react';

function Counter() {

const [count, setCount] = useState(0); // Initial count is 0

const increment = () => setCount(count + 1); // Increment count by 1

return (

<div>

<p>Count: {count}</p> {/* Displays the current count */}

<button onClick={increment}>Increment</button> {/* Button to increment */}

</div>

);

export default Counter;

What Happens:

 count holds the current value of the counter.

 The increment function is triggered when the button is clicked, updating count with the new
value (count + 1).
 React will re-render the component and update the displayed count.

3. Practical Example: Toggle Component

Now, let's create a toggle component that switches between two states: "On" and "Off". This is
another example of how useState can manage binary values.

import React, { useState } from 'react';

function Toggle() {

const [isOn, setIsOn] = useState(false); // Initial state is false (Off)

const toggle = () => setIsOn(!isOn); // Toggle between true and false

return (

<div>

<p>The light is {isOn ? "On" : "Off"}</p> {/* Conditional rendering */}

<button onClick={toggle}>Toggle Light</button> {/* Button to toggle */}

</div>

);

export default Toggle;

Explanation:

1. const [isOn, setIsOn] = useState(false);

o This creates a boolean state isOn which is initialized to false (indicating "Off").

2. toggle function:

o It flips the value of isOn. If isOn is true, it becomes false, and vice versa. This is
achieved with !isOn (the negation operator).

3. When the button is clicked, the state changes, and React re-renders the component with the
new value. If isOn is true, the text "On" is displayed, otherwise "Off".

4. Advanced Example: Text Input and State

Let's take a look at a more interactive example, where the state is used to manage form input.
import React, { useState } from 'react';

function TextInput() {

const [text, setText] = useState(''); // Initial state is an empty string

const handleChange = (e) => setText(e.target.value); // Update state on input


change

return (

<div>

<input

type="text"

value={text} // Bind the input field to the state

onChange={handleChange} // Handle input change

/>

<p>You typed: {text}</p> {/* Display the typed text */}

</div>

);

export default TextInput;

Explanation:

1. State: const [text, setText] = useState(''); initializes an empty string for text.

2. handleChange updates the state with the current value of the input field using
setText(e.target.value).

3. Input field:

o The value attribute binds the input field to the state, so when the state changes, the
input reflects the updated value.

o The onChange event is triggered whenever the user types into the input field,
updating the state.

As a result, the text typed in the input field is always displayed below the input field.
5. Example: Multiple States in a Component

You can use multiple useState hooks to manage different pieces of state in a single component.

import React, { useState } from 'react';

function MultipleStates() {

const [count, setCount] = useState(0); // Count state

const [name, setName] = useState(''); // Name state

const increment = () => setCount(count + 1);

const handleNameChange = (e) => setName(e.target.value);

return (

<div>

<p>Count: {count}</p>

<button onClick={increment}>Increment</button>

<input

type="text"

value={name}

onChange={handleNameChange}

placeholder="Enter your name"

/>

<p>Your name is: {name}</p>

</div>

);

export default MultipleStates;

Explanation:

 count and name are two separate pieces of state managed by two useState hooks.
 Clicking the "Increment" button updates the count state, while typing in the input updates
the name state.

 The component re-renders whenever either state changes.

Summary of useState:

 useState is a hook that allows functional components to have state.

 The syntax is const [state, setState] = useState(initialValue).

o state: Holds the current value.

o setState: Function used to update the state.

o initialValue: Initial state value when the component first renders.

 useState triggers a re-render when the state changes, making React applications interactive.

 You can use useState to manage various types of data, such as numbers, strings, booleans, or
objects, and even use multiple states in a component.

You might also like