Master ⚛️React Hooks In 10 minutes ?-3
Master ⚛️React Hooks In 10 minutes ?-3
<pre>
{JSON.stringify(data, null, 2)}
</pre>;
)
}
Accessing Global State with
Context
useContext helps to use values from
React Context without prop drilling.
function FocusInput() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} />
<button onClick={() =>
inputRef.current.focus()}>
Focus
</button>
</div>
);
}
State Management with
Reducers
useRef is an alternative to useState for
complex state logic.
function FocusInput() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} />
<button onClick={() =>
inputRef.current.focus()}>
Focus
</button>
</div>
);
}
Optimizing Performance with
Memoization
useMemo caches expensive calculations
between renders.
return (
<div>
<p>Count: {count}</p>
<Button handleClick={increment} />
</div>
);
}
Syncing with the DOM Before
Paint
useLayoutEffect runs synchronously
after DOM mutations but before the
browser repaints.
function Box() {
const boxRef = useRef(null);
useLayoutEffect(() => {
boxRef.current.style.transform =
"scale(1.2)";
}, []);
useImperativeHandle(ref, () => ({
focus: () =>
inputRef.current.focus(),
}));
function App() {
const inputRef = useRef();
return (
<div>
<CustomInput ref={inputRef} />
<button onClick={() =>
inputRef.current.focus()}>Focus
Input</button>
</div>
);
}
Debugging Custom Hooks
useDebugValue helps to display debug
information in React DevTools.
function useCustomHook(value) {
const [state, setState] =
useState(value);
useDebugValue(state > 5 ? "High" :
"Low");
return [state, setState];
} function App()
{
const [count, setCount] =
useCustomHook(3);
return <button onClick={() =>
setCount(count + 1)}>Count: {count}
</button>;
}
generates stable unique IDs for
elements.
useId generates stable unique IDs for
elements.
function Form() {
const id = useId();
return (
<div>
<label htmlFor={id}>Name:</label>
<input id={id} type="text" />
</div>
);
}