Overview React's useState and useEffect Hooks


Hooks are an important topic in React, and understanding common hooks like useState and useEffect is crucial for developing React applications.

useState Hook:

The useState hook provides functional components with their own internal state. It returns a pair of value:

  1. the current value
  2. a function to update that value

A common example using a counter:

In this example, the useState hook defines the count state variable and the setCount function used to update the state. The initial value of count is set to 0.

useEffect Hook:

The useEffect hook allows you to perform side effects in functional components. It is somewhat similar to lifecycle methods like componentDidMount and componentDidUpdate. This hook can be used to fetch data, subscribe to events, or any other action that has side effects.

An example from rendering returned API data:

In this example, the useEffect hook fetches data from a made up API endpoint when the component mounts for the first time. The empty array passed in is the dependency array and makes the hook run only once. The fetched data is stored in the data state variable by use of the setData function.