React Hooks are special functions that let you "hook into" React features and lifecycle methods within functional components. Introduced in React 16.8, hooks provide a way to manage state, side effects, context, refs, and more without needing to write class components. They have significantly simplified React development by making complex logic easy to share and reuse among components.
Common Hooks and Their Usage
1. useState
The useState hook allows you to add state to a functional component.
Syntax:
const [state, setState] = useState(initialState);
Example:
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>
);
}
2. useEffect
The useEffect hook allows you to perform side effects in function components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in class components.
Syntax:
useEffect(() => {
// Side effect code
return () => {
// Optional cleanup code
};
}, [dependencies]); // dependencies are optional
Example:
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup on unmount
}, []); // Empty array means this effect runs once after initial render
return <p>{seconds} seconds have elapsed since you opened this page.</p>;
}
3. useContext
The useContext hook allows you to subscribe to a React context without introducing nesting.
Syntax:
const value = useContext(MyContext);
Example:
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ backgroundColor: theme === 'dark' ? '#333' : '#FFF' }}>
I am styled by theme context!
</button>
);
}
4. useReducer
The useReducer hook is an alternative to useState. It is used when you have complex state logic or when the next state depends on the previous one.
Syntax:
const [state, dispatch] = useReducer(reducer, initialState);
Example:
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' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
5. useRef
The useRef hook allows you to persist values across renders without causing re-renders. It's primarily used to access or modify DOM elements.
Syntax:
const refContainer = useRef(initialValue);
Example:
import React, { useRef } from 'react';
function TextInputWithFocusButton() {
const inputRef = useRef(null);
const onButtonClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</div>
);
}
Custom Hooks
Custom hooks are a way to reuse stateful logic across components. A custom hook is a JavaScript function whose name starts with "use" and that may call other hooks.
Example:
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(url);
const result = await response.json();
setData(result);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
}
fetchData();
}, [url]);
return { data, loading, error };
}
export default useFetch;
Summary
React Hooks have transformed how components are written, making it easier to manage state and lifecycle events in functional components. Common hooks like useState, useEffect, useContext, useReducer, and useRef greatly simplify state management, side effects, context usage, complex state logic, and accessing DOM elements. Custom hooks provide a way to modularize and reuse stateful logic. By adopting hooks, you can write cleaner, more maintainable React code that's easier to test and understand.