React Js / Basics / state
State
-
1. Note
1. In React, state is a JavaScript object that holds data
2. When the state of a component changes, React automatically re-renders that component and its children
Create state
const [state, setState] = useState(initialValue); state → current state value.
setState → function to update the state.
initialValue → starting value (string, number, array, object, etc.).
-
2. Example
1.Basic Example: Counter
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( ); } export default Counter;Count: {count}
2. Handling Text Input (Form)
function TextInput() { const [text, setText] = useState(""); return ( setText(e.target.value)} />); }You typed: {text}
3. State as Object
function Profile() { const [user, setUser] = useState({ name: '', age: 0 }); const updateName = () => { setUser(prev => ({ ...prev, name: 'Manoj' })); }; return ( ); }Name: {user.name}
4. Array State
function TodoList() { const [todos, setTodos] = useState([]); const addTodo = () => { setTodos([...todos, "New Task"]); }; return ( ); }-
{todos.map((item, index) =>
- {item} )}
5. Multiple State Variables
const [count, setCount] = useState(0); const [isVisible, setIsVisible] = useState(true);
MANVIA BLOG