React Hooks
Introduction
Before React Hooks were introduced, managing state and lifecycle methods was only possible using class components.
This often resulted in long, complex code that was read and maintain.
React Hooks, introduced in React 16.8, completely changed how developers write React components. Hooks allow you to use powerful React features like state, side effects, and easier to understand.
Most commonly used hooks
- useState
- useEffect
What Are React Hooks?
Hooks are special functions provided by React that let you "hook into"
React features.
With Hooks, you can
- Store and update state
- Run code when a component loads or updates
- Fetch data from APIs
- Interact with the browser (like updating the document title)
Hooks only work in functional components and must follow 2 simple rules
1. Call Hooks at the top level of your component
2. Only call Hooks from React functions
Understanding useState
The useState hook allows you to add state to a functional component
Basic Syntax
stateValue - current state
setStateValue - function to update the state
initialValue - starting value of the state
Example: Counter App
How it works
- The component starts with count = 0
- Clicking the button updates the state
- React automatically re-renders the UI
This makes UI updates simple and predictable
Why useState is important
- Eliminates the need for class components
- Makes code shorter and more readable
- Encourages better component design
- Ideal for forms, counters, toggles, and UI interactions
Understanding useEffect
The useEffect hook is used to handle side effects in React components.
What is a Side Effect?
A side effect is any operation that affects something outside the component, such as
- Fetching data from an API
- Updating the document title
- Setting timers
- Subscribing to events
Basic Syntax
Example 1: Run Once on Component Load
- Empty dependency array []
- Effect runs only once, similar to componentDidMount
Example: Run When State Changes
- Effect runs every time count changes
- Useful for syncing UI with external systems
Common useEffect Use Cases
- Fetching API data
- Updating browser title
- Listening to window resize
- Handling timers and intervals
- Cleaning up subscriptions
Why Hooks Make React Better
Hooks provide several advatages
- Cleaner and shorter code
- No need for complex lifecycle metods
- Better seperation of logic
- Easier reuse of functionality
- Improved readability and maintainabilty
Modern React development heavily relies on Hooks, and most new projects avoid class components entirely.
Comments
Post a Comment