State is the interface between your data from any kind of backend or local change and the representation of this data with UI-elements in the frontend. State is able to keep the data of different components in sync because each state update will rerender all relevant components.
The state of a component is like the props which are passed to a component,
a plain JavaScript object containing information that influences the way a component is rendered.
In comparison, to the props, the state can be changed by the component itself
by calling setState
which will trigger a re-render of the component.
The state API of React is really simple at all and doesn’t add too much complexity
to your application.
Your component dependencies and the size and complexity of your app grows you will find yourself by pushing the state up in your component-tree to inject the relevant state in several components. The distance between your states location and your components which need a certain part of the state will increase.
This leads to prop drilling, meaning passing props through components which don’t need the props but their children do. You want to avoid this because it increases the complexity, for example during a refactoring.
The Context API
was added to React in version 16.3.0 earlier
this year.
Context provides a way to pass data through the component tree without having to
pass props down manually at every level.
Context is designed to share data that can be considered global
for a tree of React components,
such as the current authenticated user, theme, or preferred language.
Install the dependencies
Install the dependencies we will need: mobx and mobx-react
We will also need to install a babel plugin so we can use ES7 decorators:
Let’s update the .babelrc
file to configure our babel plugins
Provider
for application in index.jsWhen I was setting up new React and Mobx project from scratch, I was getting the following warning in VSCode.
Experimental support for decorators is a feature that is subject to change in a future release.
Set the experimentalDecorators
option to remove this warning.
Create jsconfig.json
file in the root directory of your project and include the following options.