DEV Community

Tom Marku
Tom Marku

Posted on

Using Hooks in React: 'useState' & 'useEffect'

React, one of the most popular JavaScript libraries for building user interfaces has undergone significant changes since the introduction of React Hooks. With Hooks, managing state and side effects in functional components has become more intuitive and flexible. In this blog, we'll explore essential React hooks, such as useState and useEffect. By the end of this blog, you'll have a firm grasp of how to leverage these hooks to build dynamic and interactive React applications.


Hooks are functions that let you "hook into" React state and lifecycle features from function components. Before the introduction of hooks, these features were only available in class components. React provides several built-in hooks to cover common use cases, and you can create custom hooks to encapsulate logic and reuse it across different components.


useState Hook:

The useState hook is fundamental for managing state in functional components. It allows you to add state to your components and update it as needed. Here's a simple example of how to use useState:

Image description

In this example, useState is used to create a piece of state, count, a function, setCount, to update it. When the "Increment" button is clicked, setCount is called with the new value, and the component re-renders with the updated state.


useEffect Hook:

The useEffect hook is essential for managing side effects, such as data fetching, DOM manipulation, and subscriptions, in your components. It replaces the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycles in class components. Here's how to use useEffect:

Image description

In this example, we use useEffect to fetch data from an API when the component mounts. The empty dependency array [] ensures that the effect only runs once after the initial render.

Top comments (0)