Monday, 4 Aug 2025
  • My Interests
  • My Saves
  • Try Intents
Subscribe
Focus - Code Reveals
  • Home
  • HTML

    What is Doctype HTML in HTML?

    By Chief Editor

    What are the different types of HTML tags?

    By Chief Editor

    What are the async and defer attributes in the “script” tag?

    By Chief Editor
    What is Symentic HTML

    What is Symentic HTML?

    By Chief Editor

    Difference between HTML Tag and HTML Element in HTML?

    By Chief Editor

    What is Block level Element and Inline Level Element?

    By Chief Editor
  • JavaScript

    What is the Event Loop in JavaScript?

    By Chief Editor

    What is a Closure in JavaScript?

    By Chief Editor

    What is Callback Hell in JavaScript?

    By Chief Editor

    What is one-way data binding in React?

    By Chief Editor

    What is Scope in JavaScript?

    By Chief Editor
    What are the Lexical Scope in JavaScript

    What are the Lexical Scope in JavaScript?

    By Chief Editor
  • Frontend Interview

    What is Position in CSS?

    By Chief Editor

    Is JavaScript a synchronous or asynchronous language?

    By Chief Editor

    How to Reverse a String in JavaScript: Two Essential Methods

    By Chief Editor

    What are the Lexical Scope in JavaScript?

    By Chief Editor

    What is Symentic HTML?

    By Chief Editor

    Difference Between position: relative and position: absolute in CSS

    By Chief Editor
  • Backend Interview

    What is props drilling in React?

    By Chief Editor

    What are the Rest and Spread operators in JavaScript?

    By Chief Editor

    How can you delay the dispatch in React?

    By Chief Editor

    What is Flex Box in CSS?

    By Chief Editor

    What is Virtual DOM in React?

    By Chief Editor

    What is Doctype HTML in HTML?

    By Chief Editor
  • Nodejs
  • JavaScript Interview
  • React Interview
  • Frontend Interview
  • Backend Interview
  • Contact Us
  • Advertise with Us
  • Complaint
  • Cookies Policy
  • Privacy Policy
  • Donate
  • 🔥
  • ReactJS
  • JavaScript
  • JavaScript Interview
  • React Interview
  • HTML
  • Frontend Interview
  • CSS
  • Redux
  • Javascript
  • System Design
Font ResizerAa
Focus - Code RevealsFocus - Code Reveals
  • My Saves
  • My Interests
  • My Feed
  • History
  • Technology
Search
  • Homepage
  • ReactJS
  • JavaScript
  • JavaScript Interview
  • HTML
  • CSS
  • Backend Interview
Have an existing account? Sign In
Follow US
© 2022 Code Reveals Inc. All Rights Reserved.
Home Blog Explain the useState and useEffect hooks in React
React InterviewReactJS

Explain the useState and useEffect hooks in React

Chief Editor
Last updated: February 16, 2025 1:52 pm
Chief Editor
Share
SHARE

Hooks are special functions in React that let you use state and other React features in functional components.
The two most commonly used hooks are:

Contents
1. useState Hook:2. useEffect Hook:Key Points:Summary:Comparison of useState vs useEffect:
  1. useState() → For managing state.
  2. useEffect() → For side effects (e.g., data fetching, subscriptions, DOM updates).

1. useState Hook:

Purpose:

The useState() hook allows you to add state to a functional component.


Syntax:

javascriptCopyEditconst [state, setState] = useState(initialValue);
PartDescription
stateCurrent state value.
setState()Function to update the state.
initialValueInitial value of the state.

Example:

javascriptCopyEditimport { useState } from 'react';

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

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

Explanation:

  • useState(0) → Initializes count state with 0.
  • setCount(count + 1) → Updates the state, triggers a re-render.

Key Points:

FeatureDescription
Re-renders ComponentComponent re-renders when state changes.
Preserves StateState persists between renders.
Can Store Any ValueState can hold numbers, strings, objects, arrays, etc.
Initial ValueCan be a value or a function returning a value.

2. useEffect Hook:

Purpose:

The useEffect() hook is used to perform side effects in functional components, such as:

  • Fetching data from an API.
  • Subscribing to events.
  • Updating the DOM.
  • Running code after every render or only when specific values change.

Syntax:

javascriptCopyEdituseEffect(() => {
  // Side effect code
  return () => {
    // Cleanup code (optional)
  };
}, [dependencies]);
PartDescription
Callback FunctionThe effect you want to run (e.g., fetching data).
Dependencies ArrayList of values to watch for changes (optional).
Cleanup FunctionOptional function to clean up resources (e.g., event listeners).

Example 1: Run on Every Render

javascriptCopyEditimport { useState, useEffect } from 'react';

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

  useEffect(() => {
    console.log(`Count is ${count}`);
  });

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
  • No dependencies array → Runs on every render.

Example 2: Run Only Once (On Mount)

javascriptCopyEdituseEffect(() => {
  console.log('Component mounted');
}, []);
  • Empty dependencies array → Runs only once when the component mounts.

Example 3: Run When State/Props Change

javascriptCopyEdituseEffect(() => {
  console.log(`Count changed to ${count}`);
}, [count]);
  • Runs only when count changes.

Example 4: Cleanup Example

javascriptCopyEdituseEffect(() => {
  const timer = setInterval(() => {
    console.log('Interval running');
  }, 1000);

  return () => {
    clearInterval(timer);
    console.log('Interval cleared');
  };
}, []);
  • Cleanup function clears the interval when the component unmounts.

Key Points:

FeatureDescription
Side EffectsUsed for data fetching, subscriptions, DOM manipulation.
DependenciesControls when the effect runs.
Cleanup FunctionPrevents memory leaks when adding event listeners or intervals.
Runs After RenderEffects run after every render by default.

Summary:

HookPurposeExample Use Case
useStateManage component stateForm inputs, counters, toggles
useEffectHandle side effectsFetching data, event listeners, subscriptions

Comparison of useState vs useEffect:

HookState ManagementSide Effects
useStateStores and updates dataDoes not handle side effects
useEffectPerforms side effectsDoes not manage state directly

Let me know if you need help with examples or deeper explanations on Hooks or React concepts! 🚀😊

Share This Article
Email Copy Link Print
Previous Article What is state in React, and what are its properties?
Next Article Explain the uesReducer and useContext hooks in React
Leave a Comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Your Trusted Source for Accurate and Timely Updates!

Our commitment to accuracy, impartiality, and delivering breaking news as it happens has earned us the trust of a vast audience. Stay ahead with real-time updates on the latest events, trends.
FacebookLike
XFollow
InstagramFollow
YoutubeSubscribe
LinkedInFollow
QuoraFollow
- Advertisement -
Ad imageAd image

Popular Posts

Difference between display none and visibility hidden in CSS?

The display: none; and visibility: hidden; properties in CSS both make elements invisible, but they…

By Chief Editor

Explain the useState and useEffect hooks in React

Hooks are special functions in React that let you use state and other React features…

By Chief Editor

How to Reverse a String in JavaScript: Two Essential Methods

Reversing a string is one of the most common beginner-level tasks in programming. It’s a…

By Chief Editor

You Might Also Like

ReactJS

What is Higher Order Component in React?

By Chief Editor
Mastering Star Rating Systems: Best Practices and Optimized Code Examples
React InterviewReactJS

Mastering Star Rating Systems: Best Practices and Optimized Code Examples

By Chief Editor
ReactJS

What are Benefits in React?

By Chief Editor
React InterviewReactJS

What is Life Cycle method in React?

By Chief Editor

Focus by CodeReveals is your dedicated platform for mastering tech interviews and advancing your development skills. Whether you’re aiming to become a Frontend Developer, Backend Developer, or simply preparing for your next big interview, we’re here to guide you every step of the way.

Our mission is to help aspiring developers gain real-world knowledge, build confidence, and succeed in technical interviews. We offer structured content, curated interview questions, coding challenges, and practical guidance — all designed by experienced professionals who understand what top tech companies are looking for.

At Improve, we don’t just teach — we prepare you to think like a developer, solve like an engineer, and present like a pro.

Join us and start improving today — because your dream tech job is within reach

Most Famous
  • HTML
  • CSS
  • JavaScript
  • NodeJS
Top Categories
  • JavaScript Interview
  • React Interview
  • Frontend Interview
  • Backend Interview
Usefull Links
  • Contact Us
  • Advertise with Us
  • Complaint
  • Cookies Policy
  • Privacy Policy
  • Donate

©2025  Code Reveals Inc. All Rights Reserved.

Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?