Hooks - useState
and useEffect
What Are React Hooks?
Hooks are special functions introduced in React v16.8 that allow functional components to use React features like state and lifecycle methods without writing class components.
1. useState Hook
The useState hook is used to add state to functional components.
It provides:
- A state variable to store data.
- A setter function to update the state. Syntax:
const [state, setState] = useState(initialValue);
Example:
import React, { useState } from 'react';
export default function MyComponent() {
const [name, setName] = useState("Guest");
const [age, setAge] = useState(0);
const updateName = () => setName("Damilare");
const updateAge = () => setAge(age + 2);
return (
<div>
<p>Name: {name}</p>
<button onClick={updateName}>Update Name</button>
<p>Age: {age}</p>
<button onClick={updateAge}>Increase Age</button>
</div>
);
}
2. useEffect Hook
The useEffect
hook allows you to perform side effects in functional components. Examples include:
- Fetching data from an API.
- Subscribing to events.
- Directly updating the DOM (e.g., changing document.title). Syntax:
useEffect(callback, [dependencies]);
- callback: The function to execute.
- [dependencies]: Array of values that the effect depends on.
Behavior Based on Dependencies:
- useEffect(() => { ... }); Runs after every re-render of the component.
- useEffect(() => { ... }, []); Runs only on mount (like componentDidMount).
- useEffect(() => { ... }, [value]); Runs on mount and whenever value changes.
Example:
import React, { useEffect, useState } from 'react';
export default function UseEffectHook() {
const [count, setCount] = useState(0);
const [color, setColor] = useState("green");
// Runs on mount and whenever count or color changes
useEffect(() => {
document.title = `Count: ${count} - Color: ${color}`;
}, [count, color]);
const incrementCount = () => setCount(count + 1);
const decrementCount = () => setCount(count - 1);
const toggleColor = () => setColor(color === "green" ? "red" : "green");
return (
<>
<p style={{ color }}>{`Count: ${count}`}</p>
<button onClick={incrementCount}>Add</button>
<button onClick={decrementCount}>Subtract</button>
<button onClick={toggleColor}>Change Color</button>
</>
);
}
Use Cases of useEffect:
- Event Listeners: Add/remove listeners (e.g., window.addEventListener).
- Fetching Data: Fetch API data when a component mounts or state changes.
- DOM Updates: Update document.title or other DOM properties.
- Cleanups: Handle cleanup tasks like unsubscribing from listeners.
Cleanup Example:
useEffect(() => {
const timer = setInterval(() => console.log('Running...'), 1000);
return () => {
clearInterval(timer); // Cleanup on unmount
};
}, []);
Key Points:
- State in Functional Components: Use useState for state variables.
- Side Effects: Use useEffect for anything that interacts with the outside world or reacts to changes in state/props.
- Dependency Array: Always specify the dependency array to avoid unnecessary renders or infinite loops.
- Cleanups: Always clean up subscriptions, intervals, or listeners in useEffect. With useState and useEffect, building React applications becomes easier and more intuitive.
Day after day.
Understanding upon understanding.
Top comments (0)