Search code examples
reactjsreact-lifecycle-hooks

React function component state is not available at ComponentWillUnmount


I need to make api call when ComponentWillUnmount. Iam using state variable to set api request. when i access the state variable from ComponentWillUnmount. the state value is default one but am expecting recently updated state.


    export const sampleComponent: React.FC<IProps> = (props: IProps) => {
    const [apiValue, setAipValue] = useState("");
    const [updateRec] = useMutation(UPDATE_REC);
    ....
    setApiValue
    ....
    
    useEffect(()=>{
    return () => {callApi(apiValue)}
    }, []);
    }
    
    const callApi = (input) => {
    updateRec({
    variables : {
    data : input
    }
    });
    }


Solution

  • Since your useEffect has empty dependencies ([]), the apiValue that is binded is only the inital value of apiValue

    A solution would be to use a ref to track value

    const apiValueRef = useRef();
    
    apiValueRef.current = apiValue;
    
    useEffect(() => {
      return () => {
        callApi(apiValueRef.current);
      }
    }, []);