Advanced React Hooks
Master useLayoutEffect, useImperativeHandle, and useId.
Advanced hooks for specific use cases.
useLayoutEffect
Runs before browser paint:
```javascript import { useLayoutEffect, useRef } from 'react';
function Tooltip() { const ref = useRef();
useLayoutEffect(() => { const { height } = ref.current.getBoundingClientRect(); // Position tooltip based on height }, []);
return <div ref={ref}>Tooltip</div>; } ```
useImperativeHandle
Customize ref value:
```javascript import { forwardRef, useImperativeHandle, useRef } from 'react';
const Input = forwardRef((props, ref) => { const inputRef = useRef();
useImperativeHandle(ref, () => ({ focus: () => inputRef.current.focus(), clear: () => inputRef.current.value = '' }));
return <input ref={inputRef} />; });
// Usage const ref = useRef(); <Input ref={ref} /> ref.current.focus(); ref.current.clear(); ```
useId
Generate unique IDs:
```javascript import { useId } from 'react';
function Form() { const id = useId();
return ( <> <label htmlFor={id}>Name:</label> <input id={id} /> </> ); } ```
Remember
- useLayoutEffect: Synchronous DOM reads - useImperativeHandle: Custom ref API - useId: Stable unique IDs - Use only when needed
> Next: Learn render optimization!