Difference Between useState and useEffect Hook in ReactJS
Last Updated :
14 Oct, 2024
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:
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:
expected ouptutWhat 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:
OutputDifferences 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.
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
What is the difference between â(â¦);â and â{â¦}â in ReactJS ?
When you write JavaScript, you can use either the "(â¦)" or "{â¦}" pattern to define objects. In ReactJS, (...); and {...} are used in different contexts and have different purposes, and are used to denote different types of code structures. What is "(â¦);" in React JS ?In ReactJS, (...); is used to de
5 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
Difference between ReactJS and Vue.js
ReactJS: ReactJS is an open-source JavaScript library created by Facebook which is used to deal with the view layer for both Web and Mobile applications. It can be provided on the server-side along with working on the client-side. Features of ReactJS: Scalability: It is reasonable for enormous scale
2 min read
Difference between NavLink and useNavigate hook
NavLink and useNavigate are two important utilities provided by the React Router library to manage navigation in a React application. While both serve the purpose of navigation, they are used in different contexts and offer distinct functionalities. In this article, we will explore the difference be
4 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
What are the differences between Redux and Flux in ReactJS ?
During the phase of applications or software development, we gather the requirements of customers to create a solution to solve the problem of customers or businesses. To solve problems we rely on different technologies and architecture patterns. for a long time, developers were using MVC (Model-Vie
10 min read
Difference Between a .js and .jsx File in React
React is a JavaScript library used for building user interfaces, especially for single-page applications. It uses a component-based structure that makes development more efficient and maintainable. In React, different file extensions are used for specific purposes: .js or .jsx for JavaScript and JSX
4 min read