react-nativereact-reduxmountdispatchunmount

How dispatch only once when mounting a page?


Good afternoon, dear friends. I now have dispatch executed on every action. I only need dispatch once when mounting the page and delete it when unmounting the page. Tell me how to do this.

const myRef = createRef<any>();


const KeyboardAvoidingWrapper: React.FC<IKeyboardAvoidingProps> = (
  props: IKeyboardAvoidingProps,
) => {
  const dispatch = useDispatch();
  dispatch(setReference(myRef));
  if (isAndroid) {
    return (
      <ScrollView ref={myRef} style={styles.scroll} contentContainerStyle={styles.scrollContent}>
        <KeyboardAvoiding>{props.children}</KeyboardAvoiding>
      </ScrollView>
    );
  }

  return (
    <KeyboardAwareScrollView
      ref={myRef}
      style={styles.scroll}
      extraHeight={40}
      contentContainerStyle={styles.scrollContent}
    >
      {props.children}
    </KeyboardAwareScrollView>
  );
};


Solution

  • Try this

    // Similar to componentDidMount
    useEffect(() => {
        const dispatch = useDispatch();
        dispatch(setReference(myRef));
    
        return () => dispatch(deleteReference(myRef)); // delete here on unmount
      }, []);
    }