React hooks have revolutionized the way we write functional components, making state management and side effects much more intuitive. If you're learning React, understanding these essential hooks is a must! In this blog, we'll break down the most important hooks with examples so you can easily grasp their usage.
React Hooks are built in functions that allow functional components to manage state and lifecycle features previously only available in class components. Introduced in React 16.8, hooks enable developers to write cleaner, reusable and more maintainable code without needing class components.
The useState hook allows functional components to manage state. It returns an array with two elements: the current state and a function to update that state.
Why use useState?
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
The useEffect hook is used to handle side effects such as fetching data, subscribing to events or manually changing the DOM. It runs after the component renders.
Why use useEffect?
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>Timer: {seconds} seconds</p>;
}
The useContext hook allows components to consume context values without manually passing props through intermediate components.
Why use useContext?
import React, { useContext, createContext } from 'react';
const ThemeContext = createContext('light');
function ThemedComponent() {
const theme = useContext(ThemeContext);
return <p>Current Theme: {theme}</p>;
}
The useRef hook is used to persist values across renders without causing re-renders. It is also useful for directly interacting with DOM elements.
Why use useRef?
The useReducer hook is used for managing complex state logic, similar to Redux, by dispatching actions to update state.
Why use useReducer?
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:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
The useMemo hook memoizes a computed value to prevent expensive calculations on every render.
Why use useMemo?
import React, { useMemo } from 'react';
function ExpensiveCalculation({ num }) {
const result = useMemo(() => {
console.log('Calculating...');
return num * 2;
}, [num]);
return <p>Double: {result}</p>;
}
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.