DEV Community

AKSH DESAI
AKSH DESAI

Posted on

useDeferredValue() Hook - web dev simplified

Folder Structure

Folder Image

App.js Code

import { useState } from 'react'
import List from './List';

export default function App() {

    const [input, setInput] = useState("");

    function handleChange(e) {
        setInput(e.target.value);
    };

    // console.log('app.js component');
    return (
        <>
            <input type="text" value={input} onChange={handleChange} />
            <List input={input} />
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

List.js Code

import { useMemo, useDeferredValue, useEffect } from 'react'


export default function List({ input }) {
    const LIST_SIZE = 20000;

    const defferedInput = useDeferredValue(input);

    const list = useMemo(() => {
        // console.log('children usememo hook');
        const l = [];
        for (let i = 0; i < LIST_SIZE; i++) {
            l.push(<span key={i}> {defferedInput} </span>)
        }
        return l;
    }, [defferedInput])

    useEffect(() => {
        console.log('input', input);
        console.log('defferedInput', defferedInput);
    }, [input, defferedInput])

    // console.log('children component');

    return list;
}
Enter fullscreen mode Exit fullscreen mode

Output

Output

Top comments (0)