Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
how to prevent stacking function callbacks while exiting a screen react/react-native

I have a local state selectedProducts holding a number representing the number of products the client has selected, while exiting the screen I want to update the number in redux so it can be viewed in the cart on a different screen.

but every time my local selectedProducts updates it stacks another function call on beforeRemove event

I know this is a noob problem but I've spent hours trying to find a solution to this problem and advice would be very helpful :)

    useEffect(()=>{
     navigation.addListener('beforeRemove', () => {
     console.log('check this', selectedProducts);
     if (!selectedProducts) {
      return;
     }
     dispatch(addToCartMultipleQty(selectedProducts));
     });
    },[selectedProducts])

selectedProducts is a number state whose initial value is null and on a button click event its value is either incremented or decremented by 1, if its previous value is null then its value is set to 1

Note: I just want to update selectedProducts state's latest value only once in redux when the screen is about to be exited/unmonted

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can try this:

useEffect(()=>{
  navigation.addListener('beforeRemove', () => {
    console.log('check this', selectedProducts);
    if (!selectedProducts) {
      return;
    }
    dispatch(addToCartMultipleQty(selectedProducts));
  });  
  return () => {
    navigation.removeListener('beforeRemove');
  }
}, [selectedProducts])
about 4 years ago · Juan Pablo Isaza Report

0

Add that in return at the end of useEffect it will work as componentWillUnmount in functional component

useEffect(() => {
    return () => {
        // Anything in here is fired on component unmount.
    }
}, [])

Edit: In Your case

  useEffect(() => {
    console.log('check this', selectedProducts);
    if (!selectedProducts) {
      return;
    }
    return () => {
      // Anything in here is fired on component unmount.
      if (selectedProducts) {
        dispatch(addToCartMultipleQty(selectedProducts));
      }
    };
  }, [selectedProducts]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!