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.
const MyFunctional = (props) => { const [state,setState] = useState(0); const helper = useRef(); useEffect(()=>{ helper.current = new HelperClass(onSuccess,onFailure); },[]) /* wish to avoid */ useEffect(()=>{ helper.current = new HelperClass(onSuccess,onFailure); },[state]) const onSuccess = (result) =>{ /* Here state == 0 */ } const onFailure = (error) =>{ /* Here state == 0 */ } }
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:
function useLatest(value) { const ref = useRef(value); ref.current = value; return ref; };
const MyFunctional = (props) => { const [state, setState] = useState(0); const latestStateRef = useLatest(state); const helper = useRef(); useEffect(() => { helper.current = new HelperClass(onSuccess, onFailure); }, []); const onSuccess = (result) => { console.log(latestStateRef.current); }; const onFailure = (error) => { console.log(latestStateRef.current); }; };