0

I'm using the useState hook to manage rendering components on screen. I want to initialize it with a component while passing in the useState function to set the screen into the component.

Here is my App.js. The error I get is in regards to passing a function into itself on initialization.

function App() {

  //useState hooks to determine which component should render

  const [screenLoaded, loadScreen] = useState(() => {
    <Home setLoadedScreen = {loadScreen}/> 
  })

  return (
    <div className="App">
      {screenLoaded}
    </div>
  );
}
Ancross
  • 25
  • 4

2 Answers2

0

The default value for useState is always in the parentheses, no curly braces are needed in this case. const [state, setState] = useState(default). This state could be change in the future with setState(new value).

OndrejHj04
  • 320
  • 2
  • 12
0

one simple method is to give your screen a name for example

<Home /> === "home-screen"
<About /> === "about-screen"

so when you pass the setState method of loadScreen into the component, you can switch them by setting the string, for example if you're in home screen and you want to switch to about screen, you'd write

setLoadedScreen("about-screen")

function App(){
 const [screenLoaded, loadScreen] = useState("home-screen")
    return (
    <div className="App">
      {screenLoaded === "home-screen" && <Home setLoadedScreen = "loadedScreen" />}

      {screenLoaded === "about-screen" && <About setLoadedScreen = "loadedScreen" />}
    </div>
  );
  
}