How to prevent state reset when calling state setter in 3rd party library
P粉835428659
P粉835428659 2023-09-10 22:56:16
0
1
568

I'm trying to convert a React class component into a React function component.

There is aonChangefunction that can be called inside and outside the component. TheuseStatehook gets the initial value when the function component function is called. When I use the old class component way everything works fine. Why does this happen and how to solve it?

const MyInput = (props) => { const { someLib, ...otherProps } = props; const [test, setTest] = useState(1); // console show 1,2,3, etc useEffect(() => { someLib && someLib.addCallback(onChange); }, []); const onChange = (event) => { setTest(test + 1) // this function can called inside MyInput, and from someLib, // when it called from someLib, 'test' is reset, but in class component everything good } }

P粉835428659
P粉835428659

reply all (1)
P粉514001887

The problem is thatonChangeis an obsolete closure. What you need to do is makeonChangelook like this:

const onChange = (event) => { setTest(oldTest => oldTest +1) }

Alternatively, you can addtestto the dependencies array inuseEffect, but make sure to clean it up. (You should do this anyway, but it’s more important now)

useEffect(() => { someLib && someLib.addCallback(onChange); return () => { someLib.removeCallback(onChange); } }, [someLib, test]);

Technically, if you are doing the latter approach, you need touseCallback

const onChange = useCallback((event) => { setTest(test + 1); }, [test]); useEffect(() => { someLib && someLib.addCallback(onChange); return () => { someLib.removeCallback(onChange); } }, [someLib, onChange]);

The advantage of this is that you don't have to trackonChange's dependencies in different places. The dependency list foronChangeis now closed.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!