By the end of this material, you will be able to:
useState hook to manage a component's state.useEffect hook to trigger an operation as a result of a side effect.useCallback and useRef.The useState hook is used to manage state within a functional component:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
Count: {count}
);
}
The useEffect hook runs code in response to component lifecycle events:
import { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup on unmount
}, []);
return Seconds elapsed: {seconds}
;
}
A React component can re-render when:
useCallback and useRef can optimize performance:
import { useCallback, useState } from 'react';
function ParentComponent() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, []);
return ;
}
import { useRef } from 'react';
function InputFocus() {
const inputRef = useRef(null);
return (
);
}
Use React Developer Tools to inspect component re-renders. The React.memo higher-order component can help prevent unnecessary renders.
React Hooks allow functional components to manage state, handle side effects, and optimize performance. Mastering hooks is essential for modern React development.