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:
useState()
→ For managing state .
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);
Part Description state
Current state value .setState()
Function to update the state .initialValue
Initial 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:
Feature Description Re-renders Component Component re-renders when state changes .Preserves State State persists between renders . Can Store Any Value State can hold numbers, strings, objects, arrays, etc. Initial Value Can 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]);
Part Description Callback Function The effect you want to run (e.g., fetching data).Dependencies Array List of values to watch for changes (optional).Cleanup Function Optional 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:
Feature Description Side Effects Used for data fetching, subscriptions, DOM manipulation . Dependencies Controls when the effect runs .Cleanup Function Prevents memory leaks when adding event listeners or intervals .Runs After Render Effects run after every render by default .
Summary:
Hook Purpose Example Use Case useState
Manage component state Form inputs, counters, toggles useEffect
Handle side effects Fetching data, event listeners, subscriptions
Comparison of useState
vs useEffect
:
Hook State Management Side Effects useState
Stores and updates data Does not handle side effects useEffect
Performs side effects Does not manage state directly
Let me know if you need help with examples or deeper explanations on Hooks or React concepts! 🚀😊