Asosiy matnga o'tish
ITIT Interview
React

Boshqa hooklar va custom hooklar

useRef, useMemo, useCallback, useReducer, useId, hooklar qoidalari va o'z hookingizni yozish.

O'rganildi: 0 / 6
Progress

Bu nima?

Hooklar funksional komponentlarga state, side effect va boshqa React imkoniyatlarini qo'shadigan use bilan boshlanadigan funksiyalar. useState va useEffect dan tashqari eng ko'p ishlatiladiganlari shu sahifada.

Hooklar qoidalari

  1. Hooklar faqat komponent yoki boshqa hookning yuqori darajasida chaqiriladi: if, sikl, ichki funksiya yoki erta return dan keyin emas.
  2. Faqat React funksional komponentlari yoki custom hooklar ichida.

Sababi: React hooklarni chaqiruv tartibi bo'yicha eslab qoladi (birinchi useState, ikkinchi useState...). Shart ichida chaqirilsa, tartib renderlar orasida o'zgaradi va state'lar aralashib ketadi.

// Noto'g'ri
if (isLoggedIn) {
  const [name, setName] = useState('');
}

// To'g'ri
const [name, setName] = useState('');
if (!isLoggedIn) return null;

useRef

Renderlar orasida saqlanadigan, lekin o'zgarganda render chaqirmaydigan quti: { current: ... }.

function SearchBox() {
  const inputRef = useRef(null);          // 1. DOM elementga havola
  const renderCount = useRef(0);          // 2. Render chaqirmaydigan qiymat
  const timerId = useRef();

  renderCount.current++;

  return (
    <>
      <input ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Fokus</button>
    </>
  );
}
useStateuseRef
O'zgarganda renderHaYo'q
Qiymatni o'qishShu renderdagi suratDoim eng so'nggi
QachonUI'da ko'rinadigan ma'lumotDOM havolalari, taymer ID, oldingi qiymat

useMemo va useCallback

// useMemo: og'ir hisob natijasini eslab qolish
const sorted = useMemo(
  () => products.toSorted((a, b) => a.price - b.price),
  [products]
);

// useCallback: funksiyaning o'zini eslab qolish (bir xil havola)
const handleSelect = useCallback((id) => {
  setSelectedId(id);
}, []);

<ProductList items={sorted} onSelect={handleSelect} />   // ProductList React.memo bilan

useCallback(fn, deps) aslida useMemo(() => fn, deps) bilan bir xil.

Qachon kerak:

  • Hisob haqiqatan og'ir (minglab elementni tartiblash, filtrlash).
  • Qiymat yoki funksiya React.memo bilan o'ralgan bolaga prop sifatida beriladi.
  • Qiymat boshqa hookning dependency'si (useEffect keraksiz qayta ishlamasligi uchun).

Har joyga qo'yish foyda emas: memoizatsiyaning o'zi ham xotira va solishtirish xarajati. Kelajakda React Compiler buni avtomatik qiladi.

useReducer

Murakkab, bir-biriga bog'liq state uchun. Mantiq komponentdan tashqarida, sof funksiyada:

function cartReducer(state, action) {
  switch (action.type) {
    case 'add':
      return { ...state, items: [...state.items, action.item] };
    case 'remove':
      return { ...state, items: state.items.filter((i) => i.id !== action.id) };
    case 'clear':
      return { ...state, items: [] };
    default:
      throw new Error(`Noma'lum action: ${action.type}`);
  }
}

function Cart() {
  const [state, dispatch] = useReducer(cartReducer, { items: [] });
  return <button onClick={() => dispatch({ type: 'clear' })}>Tozalash</button>;
}

useId

Server va klientda bir xil bo'ladigan unikal ID (label va ARIA uchun):

const id = useId();
<label htmlFor={id}>Email</label>
<input id={id} />

Custom hooklar

Takrorlanadigan state mantiqini qayta ishlatish uchun. Nomi use bilan boshlanadi va ichida boshqa hooklar chaqiriladi:

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    try {
      const saved = localStorage.getItem(key);
      return saved !== null ? JSON.parse(saved) : initialValue;
    } catch {
      return initialValue;
    }
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

function useDebounce(value, delay = 300) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return debounced;
}

// Ishlatish
const [theme, setTheme] = useLocalStorage('theme', 'light');
const debouncedQuery = useDebounce(query);

Har bir komponent custom hookdan o'z state'ini oladi: hooklar state'ni emas, mantiqni ulashadi.

Intervyu savollari

Ushbu sahifada