0

im new on react. im using react 18, so my problem is.. i dont know what just happen, when i dispatched the action and call it with useeffect, react just render the component twice, it will solve if i remove the strcitmode, but i dont want to, can somebody help? so in my view, the paypal button get rendered twice if i'm not remove the strictmode. i think there's something wrong on useeffect..

orderScreen.jsx

const dispatch = useDispatch();
const [sdkReady, setSdkReady] = useState(false);
useEffect(() => {
    const addPaypalScript = async () => {
      const res = await axios.get(`http://localhost:8000/api/config/paypal`);
      const data = await res.data;
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = `https://www.paypal.com/sdk/js?client-id=${data}`;
      script.async = true;
      script.onload = () => {
        setSdkReady(true);
      };
      document.body.appendChild(script);
      return data;
    };
    (async () => await addPaypalScript())();

    if (!order || success) {
      dispatch(orderDetail(orderId));
    } else if (!order.isPaid) {
      if (!window.paypal) {
        return addPaypalScript();
      } else {
        setSdkReady(true);
      }
    }
    return () => {
      dispatch(orderPayReset());
    };
  }, [dispatch]);

return(
     <PayPalButton
        amount={order.totalPrice}
        onSuccess={successPaymentHandler}
      />
)
0

1 Answer 1

1
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions: Class component constructor, render, and shouldComponentUpdate methods

More Info : React Docs

4
  • the doc say "Lifecycles will not be double-invoked in production mode." so in production mode, the button will not get render twice? i really confused with this mate, sorry hehe Commented Jul 2, 2022 at 6:41
  • Yes in production you won't face that issue Commented Jul 2, 2022 at 6:42
  • Below Youtube video will help you understand the reason behind strict mode calling twice in development, if You have time then sure to checkout youtube.com/watch?v=j8s01ThR7bQ Commented Jul 2, 2022 at 6:44
  • 1
    If you install React Devtools Chrome Extension, you will see a double log but with one grayed which is it is for development purpose
    – deta utama
    Commented Jul 2, 2022 at 7:14

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.