![]() That is the great benefit of the context: it removes the burden of passing down data through the intermediate components. and intermediate components don't have to pass down the userName prop. The hook is called with the context as an argument and returns the user name value. Value prop of the provider component is important: this is how you set the value of the context.įinally, becomes the consumer of the context by using the built-in useContext(UserContext) hook. Second, inside the component, the application's child components are wrapped inside the user context provider. Let's look into more detail at what has been done.įirst, const UserContext = createContext('Unknown') creates the context that's going to hold the user name information. The simplest way to pass data from a parent to a child component is when the parent assigns props to its child component: Including the components that are indirectly affected by the context - the ancestors of context consumers! 3. During testing, you'll have to wrap the consumer components into a context provider. Secondly, adding context complicates unit testing of components. Creating a context, wrapping everything in a provider, and using the useContext() in every consumer - increases complexity. On the other side, you should think carefully before deciding to use context in your application.įirst, integrating the context adds complexity. Context solves the props drilling problem: when you have to pass down props from parents to children. The main idea of using the context is to allow your components to access global data and re-render when that global data is changed. If the consumer isn't wrapped inside the provider, but still tries to access the context value (using useContext(Context) or ), then the value of the context would be the default value argument supplied to createContext(defaultValue) factory function that had created the context. If the context value changes (by changing the value prop of the provider ), then all consumers are immediately notified and re-rendered. You can have as many consumers as you want for a single context. Again, in case the context value changes, will re-call its render function.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |