![]() ![]() The React docs include a section Before You Use Context for a reason. You won't be able to easily see which data is being used where, as it's the case with props. ![]() But here I am referring to using plain context + ùseState / ùseReducer.īesides the extra re-renders it can become hard to keep track of the data flow in your application. Note: There are ways to combine context with other techniques like subscriptions to mitigate this issue. (A few extra renders are not an issues at all but it can get out of control if a lot of components and their children re-render.) Only in that case, you don't end up with a lot of extra re-renders. Ask yourself if consumers mostly consume the majority of the state. Instead, you should split the state up and create separate contexts like AuthContext, ThemeContextetc. This is called an extra or unnecessary re-render.įor that reason, it is bad practice to have a single, huge state provided by a context. Even if only b changes ComponentA will re-render – for no reason, it will render the same content. Example: ContextA provides the state and ComponentA reads only a. It does not matter if a component actually uses the piece of the state that has changed. The context API has a major issue: The Issue With Using React Context API for StateĬonsumers of a context always re-render if the state provided by the context changes. This is an excerpt from the React Context API docs:Ĭontext provides a way to pass data through the component tree without having to pass props down manually at every level.īy combining React's state-related hooks ( useState and useReducer) with React context you can provide a shared state to all components nested within the contexts Provider. React's Context API was created to mitigate this issue. It would pollute the code and ruin the Developer Experience (DX). But in any application but a very simple one that would require us to pass down the state several levels down the tree and through components that are not using the state themselves at all. Technically we could just place our whole state at our top-level component and pass it down the React element tree to the components that need access to the state. They make context not always the best choice for global state. There are characteristics of React Context that you should be aware of. It is easy to use and we are used to it because a lot of libraries leverage them. React's Context API is a popular choice for global state (my definition: state that is shared amongst components). ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |