You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Used when some data needs to be accessed by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult. Examples include authenticated user, theme, preferred language
The issue of passing unused props to intermediate components in order to pass it down to a lower level component
Instead of this
<Pageuser={user}avatarSize={avatarSize}/>// ... which renders ...<PageLayoutuser={user}avatarSize={avatarSize}/>// ... which renders ...<NavigationBaruser={user}avatarSize={avatarSize}/>// ... which renders ...<Linkhref={user.permalink}><Avataruser={user}size={avatarSize}/></Link>
We can pass an entire component
functionPage(props){constuser=props.user;constuserLink=(<Linkhref={user.permalink}><Avataruser={user}size={props.avatarSize}/></Link>);return<PageLayoutuserLink={userLink}/>;}// Now, we have:<Pageuser={user}avatarSize={avatarSize}/>// ... which renders ...<PageLayoutuserLink={...}/>
// ... which renders ...<NavigationBaruserLink={...}/>
// ... which renders ...{props.userLink}
Which means we only pass one prop rather than two.
The issue with this is that we are moving complexity higher up the tree making them more complicated and forces lower-level components to be more flexible than you want.
How to use Context
Basically global state
constMyContext=React.createContext(defaultvalue)<MyContext.Providervalue={}>
...
</MyContext.Provider>
class MyClass extends React.Component {componentDidMount(){letvalue=this.context;/* perform a side-effect at mount using the value of MyContext */}
componentDidUpdate() {letvalue=this.context;/* ... */}
componentWillUnmount() {letvalue=this.context;/* ... */}
render() {letvalue=this.context;/* render something based on the value of MyContext */}}MyClass.contextType=MyContext;
The text was updated successfully, but these errors were encountered:
Composition
Containment
Context
Used when some data needs to be accessed by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult. Examples include authenticated user, theme, preferred language
The issue of passing unused props to intermediate components in order to pass it down to a lower level component
Instead of this
We can pass an entire component
Which means we only pass one prop rather than two.
The issue with this is that we are moving complexity higher up the tree making them more complicated and forces lower-level components to be more flexible than you want.
How to use Context
Basically global state
The text was updated successfully, but these errors were encountered: