Chuck's Academy

Basic React

State and Lifecycle with Hooks

In React, handling state and lifecycle of components is crucial for building dynamic user interfaces. Before the introduction of hooks, these functionalities were only available in class components. However, with the arrival of hooks in React version 16.8, we can now manage state and side effects declaratively in functional components.

In this chapter, we will explore the two most commonly used hooks: useState and useEffect. These hooks allow you to manage the local state of components and handle side effects such as DOM updates or API calls.

State Management with useState

The useState hook allows you to add state to functional components. In class components, state was managed through this.state and this.setState(). With useState, state is handled more simply and declaratively.

useState Example

Here is an example of how to use useState to manage the state of a counter:

jsx
"In this code, we declare a functional component called Counter. We use the useState hook to create a state variable count, initialized at zero, and a function setCount to update the state. Each time the button is clicked, the counter increases by one."

In this example, useState returns a pair of values: the current state (count) and a function to update the state (setCount). Every time the button is pressed, the state is updated, and React re-renders the component with the new value of count.

Initial State in useState

The value you pass to useState is the initial state. In the previous example, the initial state is 0. You can also initialize the state using a function if the initialization is more complex:

jsx
"In this example, we use a function to calculate the initial value of the count state. This is useful when the initial state requires a complex calculation."

This way, you can optimize performance by calculating the initial state only once when the component mounts.

Handling Side Effects with useEffect

The useEffect hook allows you to handle side effects in functional components. Side effects are operations that affect external parts of the component, such as DOM updates, API calls, or setting up timers.

The useEffect runs after the component has been rendered. You can think of it as a combination of the lifecycle methods componentDidMount, componentDidUpdate, and componentWillUnmount from class components.

Basic Example of useEffect

Here is an example of how to use useEffect to update the page title every time the counter value changes:

jsx
"In this example, the useEffect hook updates the document title every time the count state changes. The second argument is an array containing count, meaning the effect only runs when the counter changes."

The useEffect takes two arguments:

  1. A function containing the code we want to execute as a side effect.
  2. A list of dependencies (in this case [count]) that tells React when to execute the effect. If any of the dependencies change, useEffect will re-run.

Conditional Effects and Cleanup

Some effects may require cleanup when the component unmounts or when the effect needs to be restarted. This can be done by returning a function from useEffect:

jsx
"In this example, we set a timer using setInterval inside the useEffect hook. When the component unmounts, we clear the interval using the cleanup function."

In this example, we establish a timer that prints "Tick" to the console every second. When the component unmounts, the timer is cleared using clearInterval.

Empty Dependencies

If you provide an empty dependencies list ([]), the effect will only run once, when the component mounts, simulating the behavior of componentDidMount in class components.

jsx
"In this example, the effect runs only once, when the component mounts. This is because the dependency array is empty, meaning it does not depend on any state or props."

Conclusion

Handling state and side effects are fundamental concepts in React, and hooks like useState and useEffect allow us to implement them declaratively in functional components. These hooks are powerful and flexible, making them essential tools for any React developer.


Ask me anything