App
componentIf you were to search through the internet and make a list of all the React apps, a number of common patterns would appear. Amongst these, you’d find that most React apps have a component called App
— just like the one generated by Create React App.
App
component so special?The truth is: absolutely nothing.
App
is just a common name for a component that wraps the rest of your app. For example, here’s the top level component generated by create-react-app:
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
You could rename this component to Application
, Root
, or IcecreamTruck
, and everything would continue as normal. But with that said, let’s talk about why the pattern is so common in the first place.
If you’ve been doing the exercises (you have, right?), then the latest version of your contacts app will have its state stored in two places:
ContactForm
componentThis is a perfectly good way of storing state. React is that it’s just JavaScript; you can manage your app’s state using whatever tools you’d like, and then just pass it to the root element as props.
But splitting your state between components and vanilla JavaScript isn’t the only way of managing state. Can you guess what the other way is?
You can store state in a root level component using setState()
!
Wrapping your app in an App
component lets you apply the React way of thinking to every little bit of your app, even the state that sits at the top level or your app. It allows you to stick to one way of storing — and thinking — about state.
App
of your ownLet’s move your contact app’s top level state into an App
component as an exercise.
I’ve supplied you with the solution to the previous exercise as a starting point — so if you haven’t yet completed the previous exercise, you’ll want to skip back and do that one first.
Your task is to create and render an App
component, which stores the current contact list as state, and passes an onAddContact
handler to the ContactForm
component to handle new contacts.
This exercise gives you a little more freedom than most exercises so far, so your answer may differ from the solution. And that’s okay! The important thing is that you give it a crack, make sure that you understand the solution, and then make any changes needed to make your code work. And after that, just click through to the next exercise!