ProCodebaseProCodebase
  • ModusA Growth OS for your business, on WhatsAppKiosqSell more. Chase less.AI InterviewerAutomated screening & AI-led interviewsXperto AIAI prep companion for candidatesAI Tools HubResume builder, learning paths & more
  • Pre-Vetted DevelopersScreened, scored and ready to interviewAI-Native DevelopersSenior engineers on an hourly basis
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
ProCodebaseProCodebase

ProCodebase Technologies builds AI products for hiring and growth, and ships software for clients as a technical consultancy. We source, screen and deliver pre-vetted developers — so you only interview high-signal candidates.

Products

  • Modus
  • Kiosq
  • AI Interviewer
  • Xperto AI
  • AI Tools Hub

Hire & build

  • Pre-Vetted Developers
  • AI-Native Developers
  • Technical Consultancy
  • MVP Development
  • Features

Resources

  • Articles
  • Topics
  • Certifications
  • Collections
  • Jobs

Company

  • About Us
  • Contact Us
  • Book a Demo
  • FAQs

© 2026 ProCodebase Technologies. All rights reserved.

  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Introduction to React Hooks: useState and useEffect

author
Generated by
Abhishek Goyan

24/08/2024

React

Sign in to read full article

React has taken the web development world by storm, offering a component-based architecture that enhances user experience and increases productivity. With the introduction of Hooks in React 16.8, developers can now utilize state and lifecycle methods in functional components—something previously only available in class components. Two of the most commonly used hooks are useState and useEffect. In this post, we’ll explore these hooks in detail.

Understanding useState

The useState hook allows functional components to manage state, just like class components do with this.state. It provides a way to declare state variables and also gives you a function to update them.

How to Use useState

Here's the general syntax for useState:

const [state, setState] = useState(initialState);
  • state: This is the current state value.
  • setState: This is a function to update the state.
  • initialState: The initial value of the state, which can be of any data type (string, number, array, object, etc.).

Example of useState

Let’s create a simple counter component that demonstrates how to use the useState hook:

import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <h1>Count: {count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> <button onClick={() => setCount(count - 1)}>Decrement</button> </div> ); } export default Counter;

In this example, we initialize count to 0. There are two buttons: one to increment the count and another to decrement it. Each time a button is clicked, the corresponding state update function (setCount) is called to change the count.

Introducing useEffect

The useEffect hook is used to handle side effects in your components. Side effects can include data fetching, subscriptions, manual DOM manipulations, and more. The great thing about useEffect is that it combines lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount into one.

How to Use useEffect

Here's the basic usage of useEffect:

useEffect(() => { // Your side effect code here return () => { // Cleanup function (optional) }; }, [dependencies]);
  • The first argument is a function that contains your side effect logic.
  • The second argument is an array of dependencies. The effect will only run when these dependencies change. If you provide an empty array ([]), the effect will only run once when the component mounts.

Example of useEffect

Let’s enhance our previous counter example to include a side effect. We will add a message that logs the count value to the console whenever it changes:

import React, { useState, useEffect } from 'react'; function Counter() { const [count, setCount] = useState(0); useEffect(() => { console.log(`Count has changed: ${count}`); }, [count]); return ( <div> <h1>Count: {count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> <button onClick={() => setCount(count - 1)}>Decrement</button> </div> ); } export default Counter;

In this example, every time the count state updates, the useEffect hook executes the effect function, logging the new count value to the console. This can be particularly useful for debugging or triggering other side effects when certain state values change.

Combining useState and useEffect

Often, you will find yourself using both useState and useEffect together in a single component. Let’s expand our example a bit further. Suppose we want to simulate fetching data from a server whenever the count changes. We'll create a mock function to represent data fetching:

import React, { useState, useEffect } from 'react'; // Mock an API call const fetchData = (count) => { return new Promise(resolve => { setTimeout(() => { resolve(`Fetched data for count: ${count}`); }, 1000); }); }; function Counter() { const [count, setCount] = useState(0); const [data, setData] = useState(''); useEffect(() => { const fetchCountData = async () => { const result = await fetchData(count); setData(result); }; fetchCountData(); }, [count]); return ( <div> <h1>Count: {count}</h1> <h2>{data}</h2> <button onClick={() => setCount(count + 1)}>Increment</button> <button onClick={() => setCount(count - 1)}>Decrement</button> </div> ); } export default Counter;

In this enhanced example, when the count updates, we fetch new data based on the current count and display the result below the count. The useEffect hook fetches the new data every time the count changes, simulating an API call asynchronously.

With React Hooks, we have powerful tools like useState and useEffect at our disposal to create responsive and interactive components. They streamline our components and enable us to manage state and side effects in a much more readable and maintainable way.

Popular tags

ReactHooksuseState

Share now!

Like & bookmark

Related collections

  • React Interview Challenges: Essential Coding Problems

    14/09/2024 · ReactJS

  • Mastering React Concepts

    24/08/2024 · ReactJS

Related articles

  • Setting Up Your React Development Environment

    24/08/2024 · ReactJS

  • Creating Metadata Driven Tree Structure in React JS

    12/09/2024 · ReactJS

  • Handling Authentication in React: A Comprehensive Guide

    24/08/2024 · ReactJS

  • Building a Pagination Component in React

    14/09/2024 · ReactJS

  • Harnessing State Management in React with useReducer

    24/08/2024 · ReactJS

  • Lists and Keys: Rendering Multiple Items in React

    24/08/2024 · ReactJS

  • Forms in React: Handling User Input

    24/08/2024 · ReactJS

Popular category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design