I'm trying to convert a React class component into a React function component.
There is aonChange
function that can be called inside and outside the component. TheuseState
hook 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 } }
The problem is that
onChange
is an obsolete closure. What you need to do is makeonChange
look like this:Alternatively, you can add
test
to the dependencies array inuseEffect
, but make sure to clean it up. (You should do this anyway, but it’s more important now)Technically, if you are doing the latter approach, you need to
useCallback
The advantage of this is that you don't have to track
onChange
's dependencies in different places. The dependency list foronChange
is now closed.