Chuck's Academy

State Management in React

Using useState and setState

To manage state in React, different methods are used depending on whether you are working with functional components or class components. useState is the hook used to manage state in functional components, while setState is the traditional method used in class components.

Using useState in Functional Components

useState is a hook that allows you to add state to functional components in React. You can declare multiple states by calling useState multiple times.

Basic Syntax:

jsx
  • state: The variable that contains the state value.
  • setState: The function used to update the state.
  • initialValue: The initial state value.

Simple Example:

jsx

In this example:

  • We initialize count to 0 using useState(0).
  • We update the state by calling setCount when the button is clicked.

Using setState in Class Components

setState is the method used to update state in class components. Unlike useState, setState performs a shallow merge of objects, making partial state updates easier.

Basic Syntax:

jsx
  • partialState: An object representing the changes in the state.
  • callback: (Optional) A function executed after the state has been updated.

Simple Example:

jsx

In this example:

  • We initialize count to 0 in the component constructor.
  • We update the state by calling this.setState with the partial state.

Key Differences

  1. Syntax and Usage:

    • useState is specific to functional components.
    • setState is specific to class components.
  2. State Management:

    • useState is simpler and allows managing multiple localized states.
    • setState performs a shallow merge, making it easier to update nested objects.
  3. State Update:

    • useState returns a new copy of the state.
    • setState can partially update the state.

Practical Example: Controlled Form

Functional Component:

jsx

Class Component:

jsx

Explanatory Image

By understanding the use of useState and setState, you can efficiently manage state in your React components, whether you prefer using functional or class components. In the next section, we will explore Event Handling and State Update, which is crucial for creating interactive React applications.


Ask me anything