Managing Component State

Tutorial 1 of 4

Managing Component State

1. Introduction

In this tutorial, we will explore how to manage state within individual React components using hooks. You'll learn how to use useState and useReducer to build dynamic and interactive UIs.

By the end of this tutorial, you will be able to:
- Understand the concept of state in React
- Use useState hook to manage component state
- Use useReducer hook for complex state logic

Prerequisites: Basic understanding of JavaScript and React.

2. Step-by-Step Guide

State is a JavaScript object that stores component's dynamic data. It allows us to create components that are interactive and can change over time.

useState Hook

useState is a Hook that lets you add React state to function components.

Example: useState

import React, { useState } from 'react';

function Counter() {
  // Declare a new state variable, which we'll call "count"
  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, useState is called with the initial state. Here, it’s 0. It returns a pair of values, the current state and a function that updates it. We're using array destructuring to assign names to them.

useReducer Hook

useReducer is an alternative to useState. It’s preferable when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

Example: useReducer

import React, { useReducer } from 'react';

const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <div>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    </div>
  );
}

export default Counter;

In the example above, useReducer accepts a reducer of type (state, action) => newState and returns the current state paired with a dispatch method.

3. Code Examples

Please refer to the code examples in the step-by-step guide above. The comments in the code explain each part and the expected result, when rendered, will be a counter that increments or decrements when the button is clicked.

4. Summary

In this tutorial, we've learned about managing state in React components using useState and useReducer hooks. The useState hook is used for simple states, while useReducer is preferable for complex state logic.

Next, you can explore other React hooks and learn how to manage side effects with useEffect. You can also read the React documentation for more information.

5. Practice Exercises

  1. Exercise 1: Create a component that toggles between two states when a button is clicked.
  2. Hint: Use useState to store the current state.

  3. Exercise 2: Create a component that increments, decrements, and resets a counter.

  4. Hint: Use useReducer to manage complex state logic.

  5. Exercise 3: Create a form with input fields for name, email, and password, and store these values in the state.

  6. Hint: Use useState to store the values of the input fields.

Solutions and tips for these exercises can be found in the React documentation and various online coding platforms. Remember, the key to mastering React state management is consistent practice.