Home > database >  How to force new state in React (Hooks) for textarea when clicking on another element?
How to force new state in React (Hooks) for textarea when clicking on another element?

Time:12-27

  • Edit reverent-breeze-cwyfw


    Problem:

    const [textareaValue, setTextareaValue] = useState(props.currentMarkdown);
    

    useState will use props.currentMarkdown as the initial value but it doesn't update the current state when props.currentMarkdown changes.


    Unrelated:

    The debounce update of the parent state can be improved by using useRef

    const timeout = useRef();
    
    const handleMarkdownChange = (newValue) => {
        if (timeout.current) {
            clearTimeout(timeout.current);
        }
        timeout.current = setTimeout(function () {
            console.log("fire");
            const items = [];
            for (let value of currentData.items) {
                if (value["id"] === currentData.active) {
                    value.markdown = newValue;
                    value.unsaved = true;
                }
                items.push(value);
            }
            setCurrentData({ ...currentData, items: items });
        }, 200);
    };
    

    using var timeout is bad because it declares timeout on every render, whereas useRef gives us a mutable reference that is persisted across renders

  • Related