September 28, 2022

useEffect hooki | Hooks qo'llanma 8

Componentning hayot siklini useEffect bilan boshqarish

CodeSandbox link

Bu darsdagi to'liq kodni quyidan topa olasiz: https://codesandbox.io/s/react-useeffect-7gknd7

Component hayot sikli(lifecycle)ni tushunish

useEffect hookidan samarali foydalanish uchun componentning hayot sikli haqida tushunchaga ega bo'lish zarur. Hayot sikl 3ta asosiy qismdan iborat: mounting, updating, unmounting. Agar siz class componentlarning hayot sikli bilan tanish bo'lsangiz bu 3lasi ComponentDidMount, ComponentDidUpdate, ComponentWillUnmount ga to'g'ri keladi.

Componentning hayot sikli bilan yaxshiroq tanishish uchun gulning hayot sikli haqida gaplashamiz. Qachonki siz gul urug'ini eksangiz, u mounted bo'ladi. Keyin u o'sgan sari updating bo'ladi, va u so'liganida unmounted bo'ladi. Componenting hayot sikli ham shunday, qachonki foydalanuvchi sahifaga tashrif buyursa, component mounted bo'ladi, statelarni yangilarkan, component ham updating bo'ladi. So'ngida foydalanuvchi sahifani tark etsa, component unmounted bo'ladi.

useEffect hookining anatomiyasi

component hayot sikli useEffect hookining 3ta turli qismlarida ifodalanadi, quyida ko'rsatilgani kabi:

useEffect(() => {
    // Mounting

    return () => {
        // Cleanup function or unmounting
    }
}, [//Updating])

Birinchi qism mounting qismi. Component birinchi marta ko'rsatilganida ya'ni user sahifaga tashrif buyurganida mounted bo'ladigan qismi. return function bu cleanup function yoki user qachon sahifani tark etganida component unmount bo'ladigan qism. Array, oxirgi qism, u yerga componentning hayoti davomida o'zgaradigan statelarni qo'yasiz. Qachonki bu yerdagi statelardan biri yangilansa useEffect qayta ishga tushadi.

useEffectdan qachon foydalanish kerak?

Componentning hayot sikli davomida ba'zi funksiyalarning ishga tushishini hohlasangiz useEffect juda foydali. Misol uchun Agar siz state o'zgarganda UI ni yangilashni hohasangiz, useEffect aynan kerakli hook. Quyidagi misolga boqing. Biz har safar user buttonni bosganida sahifadagi nomini o'zgarishini hohlaymiz. useEffect va useState yordamida.

Componentingizni yarating

import React, { useState } from "react"

const Button = () => {
    const [count, setCount] = useState(0)

    return <button onClick={() => setCount(count + 1)}>Siz {count} marta bosdingiz</button>;
}

export default Button

Import useEffect

useEffect dan foydalanish uchun faylning yuqori qismida uni import qilib olishimiz kerak.

import React, { useState, useEffect } from "react"

useEffectni ifodalash

useEffect(() => {
		document.title = `Siz ${count} marta bosdingiz.` // Bu mounting qismi
}, [])

Tab ning title i "Siz 0 marta bosdingiz." ga o'zgarganin i ko'rasiz, chunki countning boshlang'ich qiymati 0.

Ammo, siz buttonni bossangiz, buttondagi text yangilanadi, tabning nomi esa o'zgarmaydi. Shuning uchun biz count stateni useEffect hookining update arrayida belgilab qo'yishimiz kerak. Shundagina har safar count o'zgarganida, useEffect ham qayta ishga tushadi va tabning nomi ham o'zgaradi.

useEffect(() => {
		document.title = `Siz ${count} marta bosdingiz.`
}, [count])

Styelar bilan yakuniy kod

import React, { useState, useEffect } from "react";
import styled from "styled-components";

const MyButton = () => {
    const [count, setCount] = useState(0);

    useEffect(() => {
        document.title = `Siz ${count} marta bosdingiz.`
    }, [count]);

    return (
        <StyledButton onClick={() => setCount(count + 1)}>
            Siz {count} marta bosdingiz
        </StyledButton>
    );
};

export default MyButton;

const StyledButton = styled.button`
    background: linear-gradient(91.4deg, #2fb8ff 0%, #9eecd9 100%);
    padding: 12px 25px;
    border: none;
    border-radius: 30px;
    color: white;
    font-weight: bold;
    font-family: Segoe UI, sans-serif;
`;