The class methods which are passed as args from the functional component, are kept ‘in memory’ and doest not reflect the updated state. I can reinitialise on state changes but wish to avoid it.
JavaScript
x
29
29
1
const MyFunctional = (props) => {
2
const [state,setState] = useState(0);
3
4
const helper = useRef();
5
6
useEffect(()=>{
7
helper.current = new HelperClass(onSuccess,onFailure);
8
},[])
9
10
/* wish to avoid */
11
12
useEffect(()=>{
13
helper.current = new HelperClass(onSuccess,onFailure);
14
},[state])
15
16
17
18
const onSuccess = (result) =>{
19
20
/* Here state == 0 */
21
22
}
23
24
const onFailure = (error) =>{
25
/* Here state == 0 */
26
27
}
28
}
29
Advertisement
Answer
You’ll need an additional ref to be able to use the latest values in an async callback.
Either
- grab
react-use
‘suseLatest
hook, - write one yourself according to the docs,
- or steal this trivial reference implementation:
JavaScript161
function useLatest(value) {
2const ref = useRef(value);
3ref.current = value;
4return ref;
5};
6
JavaScript
1
17
17
1
const MyFunctional = (props) => {
2
const [state, setState] = useState(0);
3
const latestStateRef = useLatest(state);
4
const helper = useRef();
5
useEffect(() => {
6
helper.current = new HelperClass(onSuccess, onFailure);
7
}, []);
8
9
const onSuccess = (result) => {
10
console.log(latestStateRef.current);
11
};
12
13
const onFailure = (error) => {
14
console.log(latestStateRef.current);
15
};
16
};
17