Two-way binding will make your React code better.

Mikhail Boutylin
Frontend Weekly
Published in
3 min readJan 14, 2022

--

Two-way binding allows creating synchronization between 2 entities, for example, application data and view. React out of the box, provides an api to get one-way binding. When we want to mutate the state, we need explicitly call updating callback:

This is done to provide owner to child update experience. So when the root state of the app gets updated, changes will propagate to children. This makes application data flow clear and predictable, however increases the amount of code to write.
In order to make a two-way binding match with react update philosophy, I’ve built a library called mlyn. The main paradigm is that every piece of the state is readable and writable. However when you write to it, the change will bubble to the root of the state, and the root state will be updated:

That’s it, the engine will update the state in the same way as on the plain react example above.

However two-way binding is not limited to the communication with UI. You can easily bind your value to the local storage. Let say you have a hook that accepts a portion of mlyn state, and target local storage key:

Now you can easily bind user name to it:

Note that you don’t need to create/pass any callbacks to update the value, it just works.
Another use-case is when you want to make changes of the state undoable / re-doable. Once again, just pass this state to the appropriate history management hooks.

The history object will contain the api to jump to any step of the state. However, it's a bit customized 2-way binding. Whenever state gets updated, the value is pushed to the history:

When a history entry is selected, this entry is written back to the state:

And note again that we don’t write a custom boilerplate for the state update, just connecting the dots. Check this code sandbox with history management for a TodoMVC app:

For more examples on 2-way binding and mlyn visit react-mlyn repo.

--

--