React Hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class component.

What are Hooks?

Hooks are functions that let you “hook into” React state and lifecycle features from function components. They don’t work inside classes.

Built-in Hooks

1. useState

The useState Hook lets you add state to function components.

useState Example
const [state, setState] = useState(initialState);

Example:

function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

2. useEffect

The useEffect Hook lets you perform side effects in function components.

useEffect(() => {
// side effect code
return () => {
// cleanup code
};
}, [dependencies]);

Example:

function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => setData(data));
}, []);
return <div>{data ? JSON.stringify(data) : "Loading..."}</div>;
}

3. useContext

The useContext Hook lets you subscribe to React context without nesting.

const value = useContext(MyContext);

Example:

const ThemeContext = React.createContext("light");
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button className={theme}>I am styled based on the theme context!</button>
);
}

Custom Hooks

Custom Hooks let you extract component logic into reusable functions.

function useCustomHook() {
// custom hook logic
return [state, setState];
}

Example:

function useWindowSize() {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
useEffect(() => {
const handleResize = () => {
setSize({
width: window.innerWidth,
height: window.innerHeight,
});
};
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return size;
}

Rules of Hooks

  1. Only call Hooks at the top level
  2. Only call Hooks from React function components
  3. Hooks must be called in the same order every render

Best Practices

  1. Keep Hooks focused and single-purpose
  2. Use custom Hooks to share logic
  3. Follow the naming convention (use prefix)
  4. Handle cleanup in useEffect
  5. Optimize with proper dependencies

Common Use Cases

  • Form handling
  • Data fetching
  • Window event listeners
  • Animation
  • Authentication
  • Theme switching

Share & Connect