React Basics: useState and useEffect
React is a JavaScript library used to build user interfaces. Two important hooks in React are useState and useEffect.
1. useState
useState is used to store and update data in a component.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
export default Counter;
Whenever the button is clicked, the count increases and the component re-renders.
2. useEffect
useEffect is used to run side effects, such as fetching API data or setting up event listeners.
import { useEffect } from "react";
useEffect(() => {
console.log("Component mounted");
}, []);
The empty dependency array [] means the effect runs after the component mounts.
Quick Summary
-
useState→ Stores and updates component state. -
useEffect→ Handles side effects. - React re-renders components when their state changes.
These two hooks are essential for building interactive React applications!
Top comments (0)