Search code examples
reactjsreact-hooksreact-suspense

How do the React.lazy(), Suspense value received and add to state variable numbers


How can we use React.lazy() and Suspense in the below example. I am getting random value from FirstComponent.js. How do I use FirstComponent value to add to newNumber and display the total. So while rendering each time, we should get different total based on the random value received. Is that possible ?

https://codesandbox.io/s/condescending-lamarr-ny680?file=/src/App.js:0-635

import React, { Suspense, useState, useEffect } from "react";
import "./styles.css";

const FirstComponent = React.lazy(() => import("./other/FirstComponent"));
const SecondComponent = React.lazy(() => import("./other/SecondComponent"));

export default function App() {
  const [newNumber, setNewNumber] = useState("");
  useEffect(() => {
   const num1 = 100;
   setNewNumber(num1);
  }, []);
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <section>
          <FirstComponent />
          {newNumber + FirstComponent}
        </section>
        <section>
          <SecondComponent />
        </section>
      </Suspense>
    </div>
  );
}

FirstComponent.js

import React, { useState, useEffect } from "react";
const FirstComponent = () => {
  const [numbers, setNumbers] = useState("");

  useEffect(() => {
    const randomNumber = [];
    const data = [10, 20, 30, 40, 50, 60];
    const random = Math.floor(Math.random() * data.length);
    randomNumber.push(data[random]);
    setNumbers(randomNumber);
  }, []);

  return <div>Hello First: {numbers}</div>;
};
export default FirstComponent;

SecondComponent.js

import React from "react";
const SecondComponent = () => {
  return <div>Hello Second</div>;
};
export default SecondComponent;

Solution

  • You need to pass a callback, as data in React flows down.

    const FirstComponent = React.lazy(() => import("./other/FirstComponent"));
    
    export default function App() {
      const [newNumber, setNewNumber] = useState(0);
      const [randomNumber, setRandomNumber] = useState(0);
    
      useEffect(() => {
        setNewNumber(100);
      }, []);
    
      return (
        <div>
          <Suspense fallback={<div>Loading...</div>}>
            <FirstComponent set={setRandomNumber} />
            {newNumber + randomNumber}
          </Suspense>
        </div>
      );
    }
    
    const FirstComponent = ({ set }) => {
      const [number, setNumber] = useState(0);
    
      useEffect(() => {
        const randomNumber = data[random];
        setNumber(randomNumber);
        set(randomNumber);
      }, [set]);
    
      return <div>Random Number: {number}</div>;
    };
    

    Edit gracious-dust-1s62g