title: How to fix memory leak issue in react native component?
body: <p><strong>Problem:</strong></p>
  <p>I have created a react native app an their I have created a formik component like this.</p>
  <pre class="lang-js prettyprint-override"><code>    export default class Wizard extends React.Component {
        static Page = ({children, parentState}) =&gt; {
          return children(parentState);
        };
      
        constructor(props) {
          super(props);
          this.state = {
            page: 0,
          };
        }
      
        next = (values) =&gt; {
          this.setState((state) =&gt; ({
            page: this.state.page + 1,
            values,
          }));
        };
      
        previous = () =&gt; {
          this.setState((state) =&gt; ({
            page: Math.max(state.page - 1, 0),
          }));
        };
      
        validate = (values) =&gt; {
          const activePage = React.Children.toArray(this.props.children)[
            this.state.page
          ];
          return activePage.props.validate ? activePage.props.validate(values) : {};
        };
      
        render() {
          const {
            children,
            loading,
            location,
            createpa,
            onpress,
            formList,
            submitted,
          } = this.props;
          const {page} = this.state;
          const {initialValues, enableReinitialize, validationSchema} = this.props;
          const activePage = React.Children.toArray(children)[page];
          const isLastPage = page === React.Children.count(children) - 1;
      
          return (
            &lt;Formik
              initialValues={initialValues}
              enableReinitialize={validationSchema &amp;&amp; !submitted}
              validationSchema={validationSchema}
              onSubmit={(values, formikActions) =&gt; {
                onpress(values, createpa, location, formList);
                setTimeout(() =&gt; {
                  formikActions.setSubmitting(false);
                }, 500);
              }}&gt;
              {(props) =&gt; (
                &lt;&gt;
                  {React.cloneElement(activePage, {parentState: {...props}})}
                  &lt;View&gt;
                    {page &gt; 0 &amp;&amp; (
                      &lt;TouchableOpacity
                        style={styles.sendButton}
                        onPress={() =&gt; this.previous()}
                        disabled={loading}&gt;
                        {loading ? (
                          &lt;Image source={spinner} style={styles.bimage} /&gt;
                        ) : (
                          &lt;AppText styles={styles.sendButtonText}&gt;
                            {strings('new-patient.pre-btn-text')}
                          &lt;/AppText&gt;
                        )}
                      &lt;/TouchableOpacity&gt;
                    )}
                    {!isLastPage &amp;&amp; (
                      &lt;TouchableOpacity
                        style={styles.sendButton}
                        onPress={() =&gt; this.next()}
                        disabled={loading}&gt;
                        {loading ? (
                          &lt;Image source={spinner} style={styles.bimage} /&gt;
                        ) : (
                          &lt;AppText styles={styles.sendButtonText}&gt;
                            {strings('new-patient.next-btn-text')}
                          &lt;/AppText&gt;
                        )}
                      &lt;/TouchableOpacity&gt;
                    )}
                    {isLastPage &amp;&amp; (
                      &lt;TouchableOpacity
                        style={styles.sendButton}
                        onPress={props.handleSubmit}
                        disabled={loading}&gt;
                        {loading ? (
                          &lt;Image source={spinner} style={styles.bimage} /&gt;
                        ) : (
                          &lt;AppText styles={styles.sendButtonText}&gt;
                            {strings('new-patient.btn-text')}
                          &lt;/AppText&gt;
                        )}
                      &lt;/TouchableOpacity&gt;
                    )}
                  &lt;/View&gt;
                &lt;/&gt;
              )}
            &lt;/Formik&gt;
          );
        }
      }
  </code></pre>
  <p>Then I have used this component in another component like this.</p>
  <pre class="lang-js prettyprint-override"><code>const NewPatient = (props) =&gt; {
    const {
      navigate,
      onpress,
      loadding,
      createpa,
      location,
      formList,
      group,
      submitted,
    } = props;
    const [intialValue, setInitialValue] = useState({});
    const [validationSchema, setValidationschema] = useState({});
  
    useEffect(() =&gt; {
      if (formList.length !== 0) {
        var intialValues = {};
        for (var groupIndex in formList) {
          for (var fieldIndex in formList[groupIndex].fields) {
            var field = formList[groupIndex].fields[fieldIndex];
            var id = field.fieldInternalName
              ? field.fieldInternalName
              : field.fieldName;
            intialValues[id] = '';
          }
        }
        setInitialValue(intialValues);
      }
    }, [formList, submitted]);
  
    useEffect(() =&gt; {
      if (formList.length !== 0 &amp;&amp; Object.keys(validationSchema).length === 0) {
        setValidationRules(formList, setValidationschema);
      }
    }, [formList, validationSchema, submitted]);
  
    const isLargeScreen = useIsLargeDevice();
  
    return (
      &lt;KeyboardAvoidingView
        style={{flex: 1, flexDirection: 'column', justifyContent: 'center'}}
        behavior=&quot;padding&quot;
        enabled
        keyboardVerticalOffset={100}&gt;
        &lt;ScrollView&gt;
          &lt;Wizard
            submitted={submitted}
            loading={loadding}
            location={location}
            createpa={createpa}
            onpress={onpress}
            formList={formList}
            validationSchema={validationSchema}
            initialValues={intialValue}&gt;
            {formList.map((groupDetails, groupIndex) =&gt; {
              return (
                &lt;Wizard.Page key={groupIndex}&gt;
                  {(formprops) =&gt; (
                    &lt;&gt;
                      &lt;SignUpField
                        errors={formprops.erros}
                        fields={formList}
                        group={group}
                        groupIndex={groupIndex}
                        {...formprops}
                      /&gt;
                    &lt;/&gt;
                  )}
                &lt;/Wizard.Page&gt;
              );
            })}
          &lt;/Wizard&gt;
        &lt;/ScrollView&gt;
      &lt;/KeyboardAvoidingView&gt;
    );
  };
  
  export default NewPatient;
  </code></pre>
  <p>And then I have used this second component in another component like this.</p>
  <pre><code>const _onPress = async (values, createpatient, location, fields) =&gt; {
    var submitObject = {};
    for (var groupIndex in fields) {
      for (var fieldIndex in fields[groupIndex].fields) {
        var field = fields[groupIndex].fields[fieldIndex];
        var id = field.fieldInternalName
          ? field.fieldInternalName
          : field.fieldName;
  
        field.userInput = values[id];
        fields[groupIndex].fields[fieldIndex] = field;
        if (field.isCommon) {
          submitObject[id] = values[id];
        }
      }
    }
    submitObject['RegistrationFormFields'] = JSON.stringify(fields);
    createpatient(submitObject);
  };
  
  const getAllFormFeild = async (getformfiled) =&gt; {
    const token = await AsyncStorage.getItem('campaign_Key');
    getformfiled(token);
  };
  
  const NewPatient = (props) =&gt; {
    let [location, setlocation] = useState(null);
    const [selectedGroup, setSelectedGroup] = useState(0);
    const [dimensions, setDimensions] = useState({window, screen});
  
    const onChange = ({window, screen}) =&gt; {
      setDimensions({window, screen});
    };
  
    useEffect(() =&gt; {
      Dimensions.addEventListener('change', onChange);
  
      return () =&gt; {
        Dimensions.removeEventListener('change', onChange);
      };
    }, []);
  
    useEffect(() =&gt; {
      if (!props.formList &amp;&amp; !props.loadding) {
        getAllFormFeild(props.getformfiled);
      }
    }, [props]);
  
    useEffect(() =&gt; {
      BackHandler.addEventListener('hardwareBackPress', handleBackButton);
  
      return () =&gt; {
        BackHandler.removeEventListener('hardwareBackPress', handleBackButton);
      };
    }, []);
  
    useEffect(() =&gt; {
      if (props.createdD) {
        _navigateOnSuccess(props.navigation);
      }
    }, [props]);
  
    useEffect(() =&gt; {
      if (!location) {
        try {
          request(
            Platform.select({
              android: PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
              ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
            }),
          ).then((res) =&gt; {
            if (res === 'granted') {
              Geolocation.getCurrentPosition(
                (position) =&gt; {
                  setlocation(position);
                },
                (error) =&gt; {
                  console.log(error);
                  Alert.alert('Location permission denied');
                },
                Platform.OS === 'android'
                  ? {}
                  : {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
              );
            } else {
            }
          });
        } catch (error) {
          console.log(error);
          Alert.alert('Location permission denied');
        }
      }
    }, [location]);
  
    return (
      &lt;View style={styles.patientView}&gt;
        {props.loadding ? (
          &lt;View style={styles.spinnerContainer}&gt;
            &lt;Image source={spinner} resizeMode={'center'} /&gt;
          &lt;/View&gt;
        ) : (
          &lt;&gt;
            &lt;View
              style={[
                styles.patientContainer,
                {height: (dimensions.window.height * 2.9) / 4},
              ]}&gt;
              &lt;AppText styles={styles.patientFormTitle}&gt;
                {strings('new-patient.form-title')}
              &lt;/AppText&gt;
              &lt;View style={styles.formContainer}&gt;
                {props.formList &amp;&amp; (
                  &lt;NewPatientForm
                    group={selectedGroup}
                    numberOfForms={props.formList.length}
                    setSelectedGroup={(value) =&gt; setSelectedGroup(value)}
                    navigate={() =&gt; _privacyNavigate(props.navigation)}
                    onpress={_onPress}
                    loadding={props.loadding}
                    submitted={props.submitted}
                    createpa={props.createpatient}
                    location={location}
                    formList={props.formList}
                    setGroup={(index) =&gt; {
                      selectedGroup(index);
                    }}
                  /&gt;
                )}
              &lt;/View&gt;
            &lt;/View&gt;
  
            &lt;View style={styles.hr} /&gt;
            &lt;View style={styles.patientBottomContainer}&gt;
              &lt;View style={styles.patientBottomView}&gt;
                &lt;TouchableOpacity onPress={() =&gt; _navigate(props.navigation)}&gt;
                  &lt;AppText styles={styles.bottomLinkText}&gt;
                    {strings('new-patient.bottom-link')}
                  &lt;/AppText&gt;
                &lt;/TouchableOpacity&gt;
              &lt;/View&gt;
            &lt;/View&gt;
          &lt;/&gt;
        )}
      &lt;/View&gt;
    );
  };
  
  const mapStateToProps = (state) =&gt; {
    return {
      mobileNo: state.signin.mobileNo,
      loadding: state.patient.loadding,
      error: state.patient.error,
      createdD: state.patient.createdD,
      submitted: state.patient.submitted,
      formList: state.patient.formList,
    };
  };
  
  const mapDispatchToProps = (dispatch) =&gt; {
    return {
      createpatient: (patient) =&gt; dispatch(patientActions.createpatient(patient)),
      getformfiled: (token) =&gt; dispatch(patientActions.getformfiled(token)),
    };
  };
  
  export default connect(mapStateToProps, mapDispatchToProps)(NewPatient);
  </code></pre>
  <p>After when I submit even though API call is a success or not this is giving me an error like this.</p>
  <pre><code> Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
          in Formik (at Wizard.js:57)
          in Wizard (at NewPatientForm.js:229)
          in RCTView (at ScrollView.js:1063)
          in RCTScrollView (at ScrollView.js:1196)
          in ScrollView (at NewPatientForm.js:228)
          in RCTView (at KeyboardAvoidingView.js:204)
          in KeyboardAvoidingView (at NewPatientForm.js:223)
          in NewPatient (at NewPatient.js:154)
          in RCTView (at NewPatient.js:152)
  </code></pre>
  <p>I was trying a lot to find out a solution to this problem from yesterday but I was unable to do so. If someone can help me to solve this issue or giving some clues to check on it is really appreciated. Thank you very musch</p>