0

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.

importJWE
  • 73
  • 7
  • 1
    You're not cleaning up that event listener correctly, for one. You might want to use a hook that does things correctly for you, such as https://github.com/streamich/react-use/blob/master/docs/useHash.md – AKX Aug 05 '21 at 07:44
  • @AKX wow. what a document! thanks! – importJWE Aug 05 '21 at 09:07

1 Answers1

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

Logic problem

gu mingfeng
  • 1,010
  • 8
  • 10