Exambodh - Practice Aptitude, Reasoning & GK Questions

Back to Articles
ReactjsUseEffect and UseState

React useState and useEffect Hooks – Explanation with Examples

Reactjs·

Share Article

Share this article on social platforms or copy the direct link.

React.js

React useState and useEffect Hooks – Explanation with Examples

React Hooks make functional components more powerful and easier to manage. Among all hooks, useState and useEffect are the most commonly used. In this article, you will learn why they are used, how they work, and where to use them with simple examples.

Quick Summary

  • useState is used to store and update data inside a component.
  • useEffect is used to run side effects such as API calls, timers, and DOM updates.
  • Both hooks are essential for building dynamic React applications.

What is useState in React?

The useState hook is used to manage state inside a functional component. State means data that can change over time.

Why use useState?

  • To store dynamic values inside a component
  • To update UI automatically when values change
  • To manage counters, forms, and toggles
  • To make functional components interactive

Syntax of useState

const [state, setState] = useState(initialValue);

state → Current value

setState → Function used to update value

initialValue → Default starting value

Example of useState

Below example shows a simple counter using useState.

import React, { useState } from "react";

function Counter() {

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

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

}

export default Counter;

Explanation

Here count stores the current value and setCount updates it. When the button is clicked, React re-renders the component.

What is useEffect in React?

The useEffect hook is used to perform side effects in a component.

Why use useEffect?

  • Fetching API data
  • Running code on component load
  • Managing timers and intervals
  • Updating DOM

Syntax of useEffect

useEffect(() => {

 // side effect code

}, [dependency]);

[] → Runs once when component loads

[value] → Runs when value changes

No dependency → Runs after every render

Conclusion

Both useState and useEffect are essential React hooks. useState manages data, while useEffect handles side effects like API calls.

Frequently Asked Questions

Why use useState in React?

It stores and updates dynamic data inside components.

Why use useEffect?

To perform side effects such as API calls and timers.

Can both hooks be used together?

Yes, usually useEffect fetches data and useState stores it.

More In Reactjs

Explore more Reactjs articles

Read more articles from the same category or open the full category archive directly.