Passing down props

Before learning about React context in depth, let's recap what we implemented in the earlier chapters, in order to get a feeling for the problem that contexts solve:

  1. In src/App.js, we defined the user state and the dispatch function:
    const [ state, dispatch ] = useReducer(appReducer, { user: '', posts: defaultPosts })
const { user, posts } = state
  1. Then, we passed the user state and the dispatch function to the UserBar component (and the CreatePost component):
    return (
<div style={{ padding: 8 }}>
<UserBar user={user} dispatch={dispatch} />
<br />
{user && <CreatePost user={user} posts={posts} dispatch={dispatch} />}
<br />
<hr />
<PostList posts={posts} />
</div>
)
  1. In the src/user/UserBar.js component, we took the user state as a prop, and then passed it down to the Logout component. We also took the dispatch function as a prop, and passed it to the Logout, Login, and Register components:
export default function UserBar ({ user, dispatch }) {
if (user) {
return <Logout user={user} dispatch={dispatch} />
} else {
return (
<React.Fragment>
<Login dispatch={dispatch} />
<Register dispatch={dispatch} />
</React.Fragment>
)
}
}
  1. Finally, we used the dispatch and user props in the Logout, Login, and Register components.

React context allows us to skip steps 2 and 3, and jump straight from step 1 to step 4. As you can imagine, with larger apps, context becomes even more useful, because we might have to pass down props over many levels.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.89.85