Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

React Hooks: useState

1. Introduction

The useState hook is a fundamental hook in React that allows you to manage state in functional components. It provides a way to add state to your components without the need for class components.

2. Key Concepts

What is State?

State refers to a component's ability to hold and manage data that can change over time. When state changes, the component re-renders to reflect the new state.

useState Syntax

const [state, setState] = useState(initialState);

Where state is the current state and setState is a function to update the state.

3. Usage

Step-by-Step Process

Note: Ensure you import useState from React before using it.
  1. Import the useState hook.
  2. import React, { useState } from 'react';
  3. Initialize the state variable and update function.
  4. const [count, setCount] = useState(0);
  5. Create a function to update the state.
  6. const incrementCount = () => setCount(count + 1);
  7. Use the state and update function in your component.
  8. 
    function Counter() {
        const [count, setCount] = useState(0);
        const incrementCount = () => setCount(count + 1);
    
        return (
            <div>
                <h1>Count: {count}</h1>
                <button onClick={incrementCount}>Increment</button>
            </div>
        );
    }
                    

4. Best Practices

  • Keep state as simple as possible.
  • Avoid using state for derived values.
  • Batch updates when possible by using functional updates.
  • setCount(prevCount => prevCount + 1);
  • Group related state variables into objects to reduce complexity.

5. FAQ

What is the difference between useState and useReducer?

useState is ideal for managing local component state, while useReducer is better for complex state logic that involves multiple sub-values or when the next state depends on the previous one.

Can useState be used with objects?

Yes, but you need to ensure that you spread the previous state when updating it to avoid overwriting other properties.