React useState

Created By: chatGPT

useState is a Hook that allows you to add state to your functional components in React. It returns an array with two elements: the current state and a function to update that state. This is excellent for managing dynamic values within your component. Here’s a basic example of how to use it.
import React, { useState } from 'react';

function Counter() {
    const [count, setCount] = useState(0);

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

export default Counter;
In the example above, we declare a state variable named count and a function setCount to update it. The useState(0) initializes count to 0. When the button is clicked, setCount(count + 1) is called, which updates the state and re-renders the component with the new count value.
const [isOnline, setIsOnline] = useState(false);

const toggleOnline = () => {
    setIsOnline(!isOnline);
};

<button onClick={toggleOnline}>
    {isOnline ? 'Go Offline' : 'Go Online'}
</button> 
You can also use useState to manage objects or arrays. Just remember to make a copy of the state and update the copy to maintain the immutability principle. Here’s how you can manage an object state safely.
const [user, setUser] = useState({
    name: '',
    age: 0
});

const updateUserName = (newName) => {
    setUser(prevUser => ({
        ...prevUser,
        name: newName
    }));
};

<input type='text' onChange={(e) => updateUserName(e.target.value)} />
For arrays, you can use similar techniques. Here’s how to manage an array of items. Use the spread operator to add or remove items efficiently.
const [items, setItems] = useState([]);

const addItem = (item) => {
    setItems(prevItems => [...prevItems, item]);
};

const removeItem = (itemToRemove) => {
    setItems(prevItems => prevItems.filter(item => item !== itemToRemove));
};
Always remember that React batches updates triggered by event handlers. This means that updating the state multiple times within a single event can be handled correctly using the functional form of state update, as shown in the examples. The functional form takes the previous state as an argument, so useState is perfect for avoiding issues related to stale closures.
const incrementCounter = () => {
    setCount(prevCount => prevCount + 1);
};

const decrementCounter = () => {
    setCount(prevCount => prevCount - 1);
};
Introduction And SetupComponentsPropsStateLifecycle MethodsHooksContext APIJsx SyntaxVirtual DomEvent HandlingFormsRoutingPerformance OptimizationError BoundariesHigher Order ComponentsRender PropsPortalsFragmentsRefsControlled ComponentsUncontrolled ComponentsMemoizationSuspenseLazy LoadingProp TypesDefault PropsConditional RenderingList And KeysAccessibility (a11y)State ManagementTestingCustom HooksUseEffectUseStateUseContextUseReducerUseMemoUseCallbackUseRefUseLayoutEffectUseImperativeHandleUseDebugValueAutomatic BatchingSuspense For Data FetchingStrict ModeForward RefsCreateContextLazyUseTransitionUseDeferredValueUseId