Let's see about hooks in REACT today. Hooks are powerful tools in react for functional components that allows us to access the state,side effects,contexts,refs etc. They are basically special functions that allows us to hook into the functional components. The basic hooks are:
1.useState: useState lets us add reactive state to functional components. When the state changes, React re-renders the component with the new value. The syntax is:
const [state, setState] = useState(initialValue);
- state: current value
- setState: function to update the value
- initialValue: starting value (number, string, object, array, etc.)
It is mainly used for:
- Track selected filters, input values, toggle states
- Dynamically update UI based on user interaction
2.useEffect: useEffect lets us run side effects after a component renders—like fetching data, setting up timers, or listening to events.The syntax is:
useEffect(() => {
// side effect logic
return () => {
// cleanup logic (optional)
};
}, [dependencies]);
It runs after render
Re-runs when dependencies change
Cleanup runs before next effect or on unmount
It is useful for:
- Fetch and render product data dynamically
- Sync UI with external sources
- Clean up timers, listeners, or subscriptions
3.useRef: useRef creates a mutable reference that persists across renders without causing re-renders. It’s great for accessing DOM elements or storing values that don’t need to trigger UI updates. The syntax is:
const ref = useRef(initialValue);
- ref.current holds the value
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
return ;
It's useful for
- Access DOM elements directly (e.g., scroll, focus)
- Store timers, previous values, or flags
- Avoid unnecessary re-renders when tracking values
Top comments (0)