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 (
                      <div>
                        <h2>Count: {count}</h2>
                        <button onClick={() => setCount(count + 1)}>Increment</button>
                      </div>
                    );
                  }
    
                  export default Counter;
    
    
                  

    2. Handling Text Input (Form)

    
    
                  function TextInput() {
                    const [text, setText] = useState("");
    
                    return (
                      <div>
                        <input
                          type="text"
                          value={text}
                          onChange={(e) => setText(e.target.value)}
                        />
                        <p>You typed: {text}</p>
                      </div>
                    );
                  }
    
    
                  

    3. State as Object

    
    
                  function Profile() {
                    const [user, setUser] = useState({ name: '', age: 0 });
    
                    const updateName = () => {
                      setUser(prev => ({ ...prev, name: 'Manoj' }));
                    };
    
                    return (
                      <div>
                        <p>Name: {user.name}</p>
                        <button onClick={updateName}>Set Name</button>
                      </div>
                    );
                  }
    
    
                  

    4. Array State

    
                    function TodoList() {
                      const [todos, setTodos] = useState([]);
    
                      const addTodo = () => {
                        setTodos([...todos, "New Task"]);
                      };
    
                      return (
                        <div>
                          <ul>
                            {todos.map((item, index) => <li key={index}>{item}</li>)}
                          </ul>
                          <button onClick={addTodo}>Add Todo</button>
                        </div>
                      );
                    }
    
    
                    

    5. Multiple State Variables

    
                      const [count, setCount] = useState(0);
                      const [isVisible, setIsVisible] = useState(true);