reactjsreact-hooksuse-stateusecallback

how can i get useState value inside useCallback (react hook)


i can't get the useState value that inside of useCallback. when i run the code below,

import React, { useCallback, useEffect, useRef, useState } from 'react';

const DBLab = () => {
    const [hashHistory, setHashHistory] = useState("initial_value");
    const [inputValue, setInputValue] = useState("");
    const didAuthMountRef = useRef(false);

    const set = useCallback(() => {
        const decodeHash = decodeURI(window.location.hash);
        console.log();
        console.log("decodeHash: " + decodeHash);
        console.log("hashHistory: "+ hashHistory);
        setHashHistory(decodeHash);
    },[hashHistory]);

    useEffect(() => {
        const startFunc = async() => {
            set();
            window.addEventListener('hashchange', set);
            didAuthMountRef.current = true;
        }
        if(!didAuthMountRef.current) {
            startFunc();
        }
    }, [set]);
    return (
        <div>
            <h1>dblab</h1>
            <h1>{hashHistory}</h1>
            <input type='text' value={inputValue} onChange={(e)=>setInputValue(e.target.value)}/>
        </div>
    )
}

export default DBLab;

in web console, i get

decodeHash: #/dblab#first

hashHistory: initial_value

which is right. but when i change url to http://localhost:3000/#/dblab#next, i get


decodeHash: #/dblab#next

hashHistory: initial_value

this is wrong. because hashHistory has not changed. but it is not useState problem. because hashHistory that i see with <h1>{hashHistory}</h1> in screen is #/dblab#next which is the right hash.

how can i get the right hashHistory inside of useCallback?.

ps. i must have to use useCallback.


Solution

  • useEffect(() => {
        const startFunc = () => {
            if(!didAuthMountRef.current) {
                set();
                didAuthMountRef.current = true;
            }
            window.addEventListener('hashchange', set);
        }
        startFunc();
        return ()=> {
            window.removeEventListener('hashchange', set);
        }
    }, [set]);
    

    Logic problem