Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Difference Between useState and useEffect Hook in ReactJS
Next article icon

Difference Between useState and useEffect Hook in ReactJS

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

ReactJS is the powerful JavaScript library used for building user interfaces especially single-page applications(SPAs). Two of the most commonly used hooks in React are useState and useEffect. These hooks make functional components more powerful by allowing them to manage the state and handle side effects.

These are the following topics that we are going to cover:

Table of Content

  • What is useState?
  • What is useEffect?
  • Differences Between useState and useEffect

What is useState?

useState is the hook that allows you to add state to functional components in React. State refers to data that can change over time and trigger re-renders of components. Before the introduction of useState only class components could manage state.

When we call useState, it returns an array with two values:

  • The Current state value
  • The Function to update the state

This allows you to manage dynamic data in your component. Every time the state changes, React re-renders the component to reflect updated values.

  • useState hook gives us a state variable and the function to update it.
  • The Component re-renders when the state changes.
  • You can have multiple state variables by calling useState multiple times.

Example: count is the state variable and setCount is a function used to update count. When the button is clicked setCount(count + 1) increases the value of the count by 1.

// App.js
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}

export default Counter;

Output:

pic-11
expected ouptut

What is useEffect?

useEffect is the hook that allows you to perform side effects in functional components. The side effect is any operation that affects something outside a component such as data fetching, interacting with the browser DOM or setting up timers.

useEffect takes two arguments:

  • 1st argument to useEffect is function that contains side effect code.
  • 2nd argument is an array of dependencies. The effect runs only when one of these dependencies changes. If array is empty then effect runs only once when component mounts.

useEffect is also used for cleanup like removing event listeners by returning function inside it. The function containing side effect logic (e.g., fetching data or updating document title). An optional array of dependencies that tells React when to re-run effect. If array is empty then effect runs only once when component mounts.

Example: In this example every time count changes useEffect runs and updates document title with new count.

// App.js
import React, { useState, useEffect } from 'react';

function Counter() {
const [count, setCount] = useState(0);

useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // This effect runs only when 'count' changes

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}

export default Counter;

Output:

pic-12
Output

Differences Between useState and useEffect

Feature

useState

useEffect

Purpose

To manage state in the functional components

To handle the side effects in functional components

Returns

The state variable and function to update it

Nothing (but can return cleanup function)

Triggered By

State updates (when update function is called)

Renders, state changes or prop changes (depends on the dependencies)

Common Uses

Managing the UI data like form inputs, toggles and counters

Fetching the data, subscriptions, timers or updating DOM

Conclusion

Both useState and useEffect are essential tools for building modern, functional components in React. useState lets you manage and update the component state while useEffect allows you to handle side effects like the data fetching, DOM manipulation and cleanup. Together they make React components more dynamic, an interactive and efficient.


Next Article
Difference Between useState and useEffect Hook in ReactJS

S

saikumarseepana
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Hooks

Similar Reads

    Difference Between useEffect and useLayoutEffect Hook in ReactJS
    In this article, we will learn about the differences between useEffect and useLayoutEffect in React with the help of an example. We will create a counter and implement it using both useEffect and useLayoutEffect to understand the differences practically. useEffectThe useEffect is used to perform sid
    5 min read
    Difference between React.memo() and useMemo() in React.
    In React applications, optimizing performance is crucial for delivering a smooth user experience. Two key tools for achieving this are React.memo() and useMemo(). While both help improve performance, they serve different purposes and are used in distinct scenarios. Table of Content What is React.mem
    3 min read
    Difference between useRef and createRef in ReactJS
    The useRef is a hook used in functional components introduced in the React version 16.8 while createRef is a react method used in React class component, both are used to create a reference to the React ElementsPrerequisites:React JSReact JS RefsReact JS useRef HookReact JS createRef methodA ref is d
    4 min read
    Difference Between useState and useReducerHook
    React offers powerful tools, like useState for simple tasks, making it a friendly companion, and useReducer for complex challenges, functioning like a superhero team. While both manage information, useState is ideal for everyday simplicity, resembling a sticky note, while useReducer shines in intric
    3 min read
    Handling Error using React useState and useEffect Hooks
    In React, handling error states is very important to provide a smooth user experience and handle unexpected errors that may occur during data fetching or asynchronous operations. By using the useState and useEffect hooks, you can easily manage error states in your React applications. In this article
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences