Top 5 React Hooks with Real-Time Examples - Code Samples
React hooks makes developer life easier
React hooks are a ground breaking addition to the React library, introduced in version 16.8. They provide a way to use stateful logic in functional components, which were previously limited to stateless components. In this blog post, we'll explore what React hooks are, why they're needed, what solutions were used before their introduction, and the use cases they address.
1. What are React Hooks? React hooks are functions that enable functional components to manage state, perform side effects, and access React features. They allow developers to use state and other React features without writing a class component.
2. Why are React Hooks Needed? Prior to the introduction of hooks, stateful logic in React components was primarily handled using class components. While class components provided the necessary functionality, they often led to complex and verbose code, making it challenging to reuse logic across components. Additionally, managing lifecycle methods and avoiding common pitfalls like 'this' binding could be cumbersome.
3. Earlier State Management Solutions: Before hooks, React provided state management primarily through class components and higher-order components (HOCs) like Redux or Context API. While Redux and Context API were powerful tools for managing global state, they added complexity to the application architecture and required additional boilerplate code.
4. Use Cases Addressed by React Hooks: React hooks address several use cases and pain points in React development:
Reusable Logic: Hooks promote code reuse by allowing logic to be encapsulated and shared across components.
Simplification: They simplify component logic and reduce boilerplate, leading to cleaner and more maintainable code.
Functional Components: Hooks enable functional components to manage state and lifecycle, making them more powerful and flexible.
Performance Optimization: They facilitate optimized renders and prevent unnecessary re-renders through memorization and optimization techniques.
In this blog post, we'll delve into the top 5 React hooks and provide real-time examples to illustrate their usage.
1. useState: Managing Component State
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Explanation:
Import the useState hook from the 'react' package.
Declare a state variable
count
and a functionsetCount
to update it, initialized with a default value of 0 using useState().Render a paragraph displaying the current count value.
Render a button that increments the count when clicked using the setCount function.
2. useEffect: Managing Side Effects
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
};
return (
<div>
<p>Data: {data}</p>
</div>
);
}
Explanation:
Import the useEffect hook from the 'react' package.
Declare a state variable
data
and a functionsetData
to update it, initialized with a default value of null using useState().Use useEffect to perform side effects, such as fetching data, after the component mounts (
[]
dependency array ensures it only runs once).Define a fetchData function to fetch data asynchronously from an API endpoint.
Update the state with the fetched data using the setData function.
Render the fetched data inside a paragraph.
3. useContext: Accessing Context
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme.background, color: theme.foreground }}>
Themed Button
</button>
);
}
Explanation:
Import the useContext hook from the 'react' package.
Import the ThemeContext created using React.createContext().
Use the useContext hook to access the current context value provided by a nearest
<ThemeContext.Provider>
.Render a button with background and text color styles based on the theme.
4. useReducer: Managing Complex State Logic
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
Explanation:
Define an initialState object representing the initial state of the counter.
Define a reducer function that takes state and action as arguments and returns a new state based on the action type.
Use the useReducer hook to manage state and dispatch actions.
Dispatch 'increment' and 'decrement' actions to update the count state.
Render the current count value and buttons to increment and decrement the count.
5. useRef: Accessing DOM Elements
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef();
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
Explanation:
Import the useRef hook from the 'react' package.
Declare a ref object
inputRef
using useRef() and attach it to the input element.Define a handleClick function that focuses the input element when the button is clicked.
Render an input element and a button to trigger focusing on the input.
Conclusion
React hooks offer a powerful way to manage state, handle side effects, access context, manage complex state logic, and interact with the DOM in functional components. By understanding and utilizing these hooks effectively, developers can build more expressive and maintainable React applications.