useState is a React hook that adds state to functional components. It returns an array with the current state value and a setter function: const [state, setState] = useState(initialValue). The setter function triggers re-renders when called to update state.
React batches multiple state updates in the same synchronous event handler for performance. This means multiple setState calls may be processed in a single re-render. In async operations, use functional updates (prevState => newState) to ensure correct state updates.
Always treat state as immutable. Use spread operator or Object.assign() for objects: setState({...state, newProp: value}). For arrays, use methods like map, filter, or spread: setState([...items, newItem]). Never mutate state directly.
State lifting involves moving state to a common ancestor component to share it between components. Implementation requires passing state and setter functions as props. Used when multiple components need to share or modify the same state.
Form state can be handled using controlled components with useState, formik/react-hook-form libraries for complex forms, or uncontrolled components with refs. Consider validation, submission handling, and error states.
State machines provide predictable state transitions, clear visualization of possible states, prevent impossible states, and make complex workflows manageable. Libraries like XState help implement state machines in React.
Derived state is calculated from existing state/props during render. Use useMemo for expensive calculations. Avoid storing derived values in state; compute them during render to prevent state synchronization issues.
Use immutable update patterns with spread operator or libraries like immer. Create new object references at each level of nesting. Consider flattening state structure when possible to simplify updates.
Handle initial state hydration, avoid state mismatches between server and client, implement proper state serialization, and consider using state management solutions that support SSR like Redux or Zustand.
useState is simpler and good for independent pieces of state, while useReducer is better for complex state logic, related state transitions, or when next state depends on previous state. useReducer follows Redux-like patterns with actions and reducers.
Context API provides a way to pass data through the component tree without prop drilling. It's useful for global state like themes, user data, or locale, but shouldn't be used for every state as it can cause unnecessary re-renders.
Implement undo/redo using an array of past states and current index. Use useReducer for complex state history management. Consider memory usage and performance implications for large state objects.
Immutability ensures predictable state updates, enables efficient change detection for rendering optimization, prevents bugs from unintended state mutations, and supports time-travel debugging features.
State synchronization can be achieved through lifting state up, using Context API, implementing pub/sub patterns with custom events, or using state management libraries. Consider performance and complexity trade-offs.
Use props directly when possible, implement getDerivedStateFromProps for class components, or use useEffect for functional components. Avoid anti-patterns like copying props to state unless needed for specific use cases.
Update UI immediately before API confirmation, maintain temporary and permanent state, implement proper rollback mechanisms for failures, and handle race conditions in concurrent updates.
Use useMemo for expensive computations, implement proper cache invalidation strategies, leverage browser storage for persistence, and consider using caching libraries like react-query for server state.
Use state for controlling animation triggers, implement proper cleanup for animation timeouts, consider using libraries like Framer Motion or React Spring, and handle edge cases during component unmounting.
Common pitfalls include: mutating state directly, not using functional updates for state depending on previous value, initializing with expensive operations without lazy initialization, and not considering batching behavior in async operations.
Custom hooks are reusable functions that encapsulate state logic and can use other hooks. They help abstract complex state management, share stateful logic between components, and follow the DRY principle. Names must start with 'use'.
Use multiple state variables for data, loading, and error states. Implement proper error boundaries, loading indicators, and cleanup for cancelled requests. Consider using custom hooks or libraries like react-query for complex data fetching.
Implement WebSocket connections in useEffect, handle connection lifecycle, update state with incoming messages, and implement proper cleanup. Consider using libraries like Socket.io or custom hooks for WebSocket state.
Cleanup functions in useEffect prevent memory leaks and stale state updates by canceling subscriptions or pending operations when component unmounts or dependencies change. Return a cleanup function from useEffect for proper resource management.
Split context into smaller, focused contexts, use React.memo for consumer components, implement value memoization with useMemo, and consider using context selectors. Avoid putting frequently changing values in context.
Local state (useState, useReducer) is component-specific and used for UI state. Global state (Context, Redux) is application-wide and used for shared data. Choose based on state scope and component coupling needs.
State persistence can be achieved using localStorage/sessionStorage with useEffect, custom hooks for storage synchronization, or state management libraries with persistence middleware. Consider serialization and hydration strategies.
Organize state by feature/domain, keep state as close as needed to components, use appropriate mix of local and global state, implement proper state normalization, and document state shape and update patterns.
Use React DevTools to inspect component state, implement logging middleware for state changes, use time-travel debugging in Redux DevTools, and add proper error boundaries and logging for state updates.
Use custom hooks for reusable state logic, implement higher-order components for state injection, use render props pattern, or leverage Context API for shared state access.