Getting Started with React Hooks
React Hooks are one of the most useful features in modern React development. They allow developers to use state and other React features inside functional components without writing class components.
React Hooks are one of the most useful features in modern React development. They allow developers to use state and other React features inside functional components without writing class components.
What is useState?
The useState hook allows us to store and update data inside a component.
For example:
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
In this example, the count variable stores the current value while setCount updates it.
Why Use Hooks?
Hooks make React components easier to write and maintain.
Some common benefits are:
Less boilerplate code
Easier state management
Reusable logic through custom hooks
Cleaner functional components
Better code organization
Another Useful Hook: useEffect
The useEffect hook is commonly used when we need to perform side effects such as fetching data or updating the document title.
import { useEffect } from "react";
useEffect(() => {
document.title = "My React App";
}, []);
The empty dependency array means the effect runs once when the component is mounted.
Important Note
Hooks should always be called at the top level of a React component or inside a custom hook.
Avoid calling hooks inside loops, conditions, or nested functions.
Conclusion
React Hooks make functional components powerful and flexible. If you are learning React, start with useState and useEffect before moving to more advanced hooks such as useMemo, useCallback, useReducer, and custom hooks.