Beginners guide to react hooks
When you start learning front-end you’ll hear a lot about JavaScript libraries especially react so What is exactly React?
React is a JavaScript library created by Facebook by the help of which we can build fast interactive reusable user interfaces
why is react so popular ?
- we can reuse components
- its fast
- good community support
- largerly used in many companies
today lets talk about react components
1.useState – managing state
2.useEffect – side effects (API calls, timers, etc.)
3.useRef – referencing DOM elements
4.useContext – global state sharing
Custom hooks (reusable logic)
- useState: It allows you to add state (data that changes) inside a function
import React, { useState } from “react”;
function Counter() {
const [count, setCount] = useState(0); // initial value = 0
return (
Count: {count}
setCount(count + 1)}>Increment
);
}
export default Counter;
2. useEffect – Handle Side Effects
Think of this as code that should run when something happens (like fetching data, updating the DOM, or running on mount).
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); // cleanup
return
Time: {seconds}s
;
}
export default Timer;
3.useContext – Share Data Easily
Passing props through multiple levels of components can be messy. With useContext
, you can share global state across your app without prop drilling.
Example use case: Sharing a theme (dark/light) or user authentication status
- useRef – Store Values Without Re-rendering
The useRef
hook is used to:
- Directly access DOM elements
- Store values between renders without causing re-renders
Example: focusing an input field automatically.