Skip to content Skip to sidebar Skip to footer

What Does The "single Source Of Truth" Mean?

I have read this article. In the 'Controlled Components' part, there is a sentence: We can combine the two by making the React state be the “single source of truth”. What d

Solution 1:

Specifically in article you linked it talks about 'controlled' and 'uncontrolled' components.

Basically, when you want to implement 'single source of truth', you want to make your components controllable.

By default input fields are not controllable which means it will render data from DOM, not state.

However, if you make your input listen to state instead (therefore making it controllable) it will not be able to change its value unless you change state.

First effect you will notice is that, once you added value property to it, when you type in, nothing will change. And if you add onChange method that changes state, it will be fully controllable component that only listens to one source of truth; state, instead of DOM events.

--

This is also related to one way data binding. It means that there is only one place which represents state of application, and your UI listens to it. And listening UI will change only if data at this place is changed, never else.

http://i.imgur.com/hJmGMqu.jpg

--

enter image description here

Also this might be useful: https://redux.js.org/docs/basics/DataFlow.html

In React-Redux applications, when your Redux is a single source of truth, it means that the only way to change your data in UI is to dispatch redux action which will change state within redux reducer. And your React components will watch this reducer and if that reducer changes, then UI will change itself too. But never other way around, because Redux state is single source of truth.

This is how it looks in Redux world:

enter image description here

A practical example would be that you have Redux store which contains items you want to display. In order to change list of items to be displayed, you don't change this data anywhere else other than store. And if that is changed, everything else related to it, should change as well.

Solution 2:

Usually, in HTML + JS, the state/value of the <input> is controlled by the browser, not javascript. If you also keep the value of such an input in javascript (for any reason), it means there are at least "two sources of truth" - what the browser thinks the value is, and what your code thinks the value is.

With React "controlled components", the two states/values always match, because React always ensures that the browser's (<input>'s) value is equal to the one you provide from javascript (using value attribute), and so effectively, there is only one "source of truth" left..

Post a Comment for "What Does The "single Source Of Truth" Mean?"