JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How do I manage state in React applications?

Asked on Sep 24, 2024

Answer

Managing state in React applications can be done using various methods, such as using React's built-in state management with hooks like useState and useReducer, or by using external libraries like Redux for more complex state management needs.
// Using useState for simple state management
        import React, { useState } from 'react';

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

            return (
                <div>
                    <p>Count: {count}</p>
                    <button onClick={() => setCount(count + 1)}>Increment</button>
                </div>
            );
        }

        export default Counter;
Additional Comment:
  • The code demonstrates the use of the "useState" hook to manage a simple counter state in a functional component.
  • "useState" initializes the state with a value of 0 and provides a function "setCount" to update the state.
  • The "Increment" button updates the state by calling "setCount" with the new value.
  • For more complex state management, consider using "useReducer" or external libraries like Redux or Context API.
  • Always ensure state updates are done in a way that React can efficiently re-render components.
✅ Answered with JavaScript best practices.
← Back to All Questions