Search code examples
javascriptreact-nativereact-functional-component

Initialise helper class in a react functional component


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 */

    }
}

Solution

  • You'll need an additional ref to be able to use the latest values in an async callback.

    Either

    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);
      };
    };