Home > Enterprise >  Rendering component in order in React
Rendering component in order in React

Time:04-27

I have two components. component A and component B. I want to render component B after component A is fully rendered. I used useEffect and uselayoutEffect hooks, but those didn't help me. What's your solution?

CodePudding user response:

Render component A with uselayoutEffect and component B with

useEffect(() => {}, [])

I specifically prefer React Lazy Loading components

CodePudding user response:

The following example is working using useEffect. Once <App /> is rendered, that means <ComponentA /> is rendered because it is one of its children, so we can use useEffect to update the state and render <ComponentB />:

const { useState, useEffect } = React

function ComponentA() {
  return <div>A</div>
}

function ComponentB() {
  return <div>B</div>
}

function App() {
  const [componentALoaded, setComponentALoaded] = useState(false)
  useEffect(() => {
    setCompALoaded(true)
  }, [])

  return (
    <div>
      <ComponentA />
      {componentALoaded && <ComponentB />}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

However, it may not be very efficient if you want to do this with a lot of components.

  • Related