top of page
Logo der Online Agentur mdwp

MobX

MobX is a state management solution that is very popular in the world of React. It stands out with its reactive nature, which allows developers to manage the state of their applications easily and effectively, without the need to manually keep track of all the changes in the application's state.

Mobx uses observables and observers to keep track of state changes. An observable is a data structure that holds state and can be observed. Observables are created with the `observable` function or `@observable` decorator. Any value can be made observable.

Whenever the state that is held by an observable changes, Mobx will automatically re-render all components that depend on this state. This automatic reaction to state changes is the core of Mobx’s philosophy.

Here is a small example of a MobX usage with React JS:

```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { observable } from 'mobx';
import { observer } from 'mobx-react';

// We create an observable state
const appState = observable({
count: 0
});

// This action updates our state
appState.increment = function() {
this.count++;
};

// Our component becomes an observer to automatically update whenever the state changes
const Counter = observer(({ state }) => (
<div>
Counter: {state.count} <br />
<button onClick={() => state.increment()}>Increment</button>
</div>
));

// We render our application
ReactDOM.render(<Counter state={appState} />, document.getElementById('root'));
```

In this code snippet, we first import the necessary libraries. Then, we create an observable state `appState` that holds a count and a function `increment` to increase the count. The `Counter` component is an observer that re-renders whenever `appState.count` changes. This component is then rendered to the HTML element with id 'root'. The increment button in the component triggers the `increment` function that increases `appState.count`, resulting in the component re-rendering with the new count.

bottom of page