React Hooks are functions that let you "hook into" React state and lifecycle features from function components. They were introduced in React 16.8 to address several problems with class components, such as difficulty in reusing stateful logic between components, the complexity of 'this' binding, and making components harder to test and understand. Hooks allow you to write functional components that can manage state, perform side effects, and more, without needing to write a class.
Key advantages of Hooks include:
1. Reusing Stateful Logic: Hooks allow you to extract stateful logic from a component so it can be tested independently and reused.
2. Cleaner Code: They help organize component logic by purpose (e.g., data fetching, subscriptions) rather than by lifecycle methods, which often had unrelated logic bundled together.
3. No Classes: You can get all the benefits of state and lifecycle features in functional components, avoiding the complexities of 'this' in JavaScript classes.
Let's delve into two fundamental Hooks:
1. `useState` Hook:
`useState` is a Hook that allows functional components to manage state. It provides a way to declare state variables inside a function component.
* Purpose: To add a state variable to your function component.
* Syntax: `const [stateVariable, setStateVariable] = useState(initialValue);`
* `stateVariable`: The current value of the state.
* `setStateVariable`: A function that lets you update the `stateVariable`. When you call this function with a new value, React will re-render the component.
* `initialValue`: The value that the state will be initialized with during the first render.
2. `useEffect` Hook:
`useEffect` is a Hook that lets you perform side effects in function components. Side effects are operations that interact with the outside world (e.g., data fetching, subscriptions, manually changing the DOM, setting up timers, logging). In class components, these would typically be handled in lifecycle methods like `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount`.
* Purpose: To perform side effects after every render (by default), or conditionally based on dependencies.
* Syntax: `useEffect(() => { /* side effect logic */ return () => { /* cleanup logic */ }; }, [dependencies]);`
* First Argument (Function): This function contains the imperative, possibly effectful code. React runs this function after every render where the dependencies have changed.
* Return Value (Cleanup Function): Optionally, the function passed to `useEffect` can return another function. This returned function is the "cleanup" function. React will run this cleanup function when the component unmounts, and also before re-running the effect due to re-renders (if dependencies change). This is crucial for preventing memory leaks (e.g., unsubscribing from subscriptions).
* Second Argument (Dependency Array): This optional array controls when the effect re-runs:
* No array: The effect runs after every render of the component.
* Empty array (`[]`): The effect runs only once after the initial render (like `componentDidMount`) and the cleanup runs only when the component unmounts (like `componentWillUnmount`).
* Array with values (`[prop1, state2]`): The effect runs after the initial render and whenever any of the values in the dependency array change. The cleanup runs before re-running the effect and when the component unmounts.
Example Code
import React, { useState, useEffect } from 'react';
function CounterAndTitleUpdater() {
// 1. Using useState for a simple counter
const [count, setCount] = useState(0);
const [message, setMessage] = useState('Hello React Hooks!');
// 2. Using useEffect for side effects
// Effect 1: Update document title based on count
// This effect runs after every render if 'count' changes.
useEffect(() => {
document.title = `You clicked ${count} times`;
console.log('useEffect 1: Document title updated.');
// Optional cleanup for this effect (not strictly necessary here but good practice)
return () => {
console.log('useEffect 1 Cleanup: Resetting title (or previous state).');
// document.title = 'React App'; // Example cleanup: reset title
};
}, [count]); // Dependency array: Effect re-runs only when 'count' changes.
// Effect 2: Simulate data fetching on component mount
// This effect runs only once after the initial render (empty dependency array).
useEffect(() => {
console.log('useEffect 2: Component mounted. Simulating data fetching...');
// Imagine fetching data from an API
const timerId = setTimeout(() => {
setMessage('Data loaded: Welcome to Hooks!');
console.log('useEffect 2: Data fetching simulation complete.');
}, 2000);
// Cleanup for this effect: Clear the timer if component unmounts
return () => {
console.log('useEffect 2 Cleanup: Clearing timeout.');
clearTimeout(timerId);
};
}, []); // Empty dependency array: Effect runs only once on mount and cleanup on unmount.
// Effect 3: Logs when 'message' state changes
// This effect runs whenever 'message' changes
useEffect(() => {
console.log(`useEffect 3: Message state changed to: "${message}"`);
}, [message]); // Dependency array: Effect re-runs only when 'message' changes.
return (
<div>
<h1>React Hooks Example</h1>
<p>You clicked the button {count} times.</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
<h2>Message from Data Fetch:</h2>
<p>{message}</p>
<button onClick={() => setMessage('New message set manually!')}>
Change Message Manually
</button>
</div>
);
}
export default CounterAndTitleUpdater;








Hooks (useState, useEffect etc.)