DEV Community

Cover image for Understand One-way Data Binding in React the easy way!

Understand One-way Data Binding in React the easy way!

Parnika-Gupta on August 09, 2021

React is a popular JavaScript library for many reasons and one of the reasons is “one-way data binding”. If you want to understand React to its cor...
Collapse
 
anuraggharat profile image
Anurag Gharat

Hi Parnika. Nice Explanation. But I think the heading is a little misleading. You mentioned about one way data binding in React and the article is about Unidirectional Data flow in React. Both are two different things.

One way data binding happens on the component level. Where the Component UI is connected and synced with the Component state.

While Unidirectional Data flow is about passing data from Higher component to lower component in Component Hierarchy.

Collapse
 
nis6 profile image
Nisha Chauhan

Just what I was looking for! Thanks a lot Anurag!

Collapse
 
harshasanapu100 profile image
Harsha • Edited

This statement made my life is easy on React. I was so confused about these 2 statements one way data binding and unidirectional data flow next tow way data binding and bidirectional data flow. Thanks for your comments. If possible could you please provide the examples of one way data binding and two way data binding in React.

Collapse
 
anuraggharat profile image
Anurag Gharat

One way data binding happens when you declare a variable with a value and attach that variable on the UI.

import React from 'react';

export default function MyComponent() {
  const [variable, setVariable] = useState('Anurag')

return (
    <div>
      <p>{variable}</p>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

As you see in the above example, I have a variable with value anurag which I am putting on the UI. The variable is attached to the UI and not the other way around. The user cannot change the value of the variable. This is one way binding - Data to the UI.

In two way data binding, the user can change the value of the variable through some action performed on the UI. Something like a form or button.

import React from 'react';

export default function MyComponent() {
  const [variable, setVariable] = useState('Anurag')

 function handleClick(){
  setVariable('New Value')
} 

  return (
    <div>
      <p>{variable}</p>
     <button onClick={handleClick} >Click Me</button>

 </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

So In short, if the Logic defines the value present on the UI, it's one way binding. If the logic defines the value on the UI and the UI can also update the value, it's two way binding.

Collapse
 
salarc123 profile image
SalarC123 • Edited

I’m curious as to why you passed a callback to the child instead of just directly passing the setText function

Collapse
 
parnikagupta profile image
Parnika-Gupta

Hey there is no particular reason I did that. Is there a reason why we should or shouldn't be using arrow functions when we can directly pass the setText function? I would love to learn more about the depth of it.

Collapse
 
r4e profile image
Richie Permana

IMHO, its just matter of simplicity and consistency.

<Child setText={ setText }>
// is the same as
<Child setText={(text) => { setText(text) }}>

// but not as
<Child setText={ setText() }>
//or
<Child setText={(text) => setText(text)}>
Enter fullscreen mode Exit fullscreen mode

CMIIW.

Thread Thread
 
parnikagupta profile image
Parnika-Gupta

I just saw a video on callbacks that made it clear for me.. I will find it again to grab a link and share if anyone needs...But what's the difference between 2nd format and the 4th one that you have shared?

Collapse
 
salarc123 profile image
SalarC123

I’m not actually sure. I’ve just always done it like this, but I don’t really see any differences between the two methods

Collapse
 
rabbimorgan profile image
Rabbi-Morgan

The setText is a useState function, calling in somewhere is won't change the state, you have to call it in it's own component for it to work.
so he is returning the setState with the new value of text from the child to the parent which will now bw executed in the parent.

Collapse
 
artydev profile image
artydev • Edited

Hello @parnikagupta ,

What do you think of this ? :

Only to see that there is a life outside React :-)

ParentChild

In case you are interested how this works, you can give an eye here : DML




// make : wrapper around createElement
const cType = (type) => (content, props) => make(type, props, content)

const h1 = cType("h1");
const div = cType("div");
const button = cType("button");
const br = () => make("br");


const cssChild= `
  border: 1px solid red; 
  padding:10px;
  background:orange;
  box-shadow: 1px 10px 20px rgba(120,80,0,0.34)
`

function Parent () {
  selectBase(div('', "background:darkorange; padding:10px; margin:10px"))
  h1("Parent")
  let c = Counter();
  br()
  button("inc child counter").onclick = () => c.incby(1);
  unselectBase()
}

function Counter () {
    selectBase(div("I am the child...", cssChild))
      let value = div("0");
      let incby = (val) =>  value.innerText = Number(value.innerText)+val
      button("inc").onclick = () => incby(1);
      button("dec").onclick = () => incby(-1);
    unselectBase()
    return { incby }
}


Parent();
Parent();
Parent()


Enter fullscreen mode Exit fullscreen mode

You can try it here : ParentChild

Regards

Collapse
 
kashyaprahul94 profile image
Rahul Kashyap • Edited

Nicely articulated. Congratulations on your first post.

It is worth to note that this holds good to any level of nesting of the components however not advised :)

Such situations can be dealt beautifully with Contexts or state management libs.

Collapse
 
parnikagupta profile image
Parnika-Gupta

Thank you Rahul! Means a lot. But this is sort of my 2nd post but this one has reached more people, I guess people liked it better than my previous one 😜
Thanks for the additional information I have added it to my knowledge of React now! Really appreciate it.

Collapse
 
dawnind profile image
Mainak Das

For the syntax highlighting add the type after the first three backticks

Collapse
 
parnikagupta profile image
Parnika-Gupta

Thanks Mainak! Will take care of it going forward.

Collapse
 
ptejada profile image
Pablo Tejada

Why there is no syntax highlighting in your code snippets?

Collapse
 
parnikagupta profile image
Parnika-Gupta

Sorry I am new here so I am not familiar with formatting. Will improve in next one for sure!

Collapse
 
hyggedev profile image
Chris Hansen • Edited

Don't be sorry. I'm new too, and barely found out about syntax highlighting! ✌️

PS+
You can totally go back and edit your post and add javascript immediately after your first three back-ticks 😀
Also, awesome article 👋

Thread Thread
 
parnikagupta profile image
Parnika-Gupta • Edited

That's great will go back and do that right away! Thank you so much.

Thread Thread
 
ptejada profile image
Pablo Tejada • Edited

This was the first article without syntax highlighting I saw. I just assume it was something done automatic like on Stackoverflow. I learned about this recently myself.

Thread Thread
 
parnikagupta profile image
Parnika-Gupta

Thanks for pointing it out though! Helped me learn a new thing. :)

Collapse
 
parnikagupta profile image
Parnika-Gupta

Ah! Thanks for calling that out I copied the working code from my VS Code but I was deleting some experimental divs I was adding so must have deleted the div closing tag by mistake! I will just correct it in a sec.

Collapse
 
alexandrefuente profile image
alexandrefuente

Great article. Thanks @parnikagupta .

Collapse
 
parnikagupta profile image
Parnika-Gupta

Thank you @alexandrefuente means a lot!

Collapse
 
capscode profile image
capscode

wonderful article

Collapse
 
parnikagupta profile image
Parnika-Gupta

Thank You!

Collapse
 
antoniomora95 profile image
Antoniomora95

Simple and useful

Collapse
 
parnikagupta profile image
Parnika-Gupta

Thank you so much!

Collapse
 
aesthytik profile image
Vipin Kumar Rawat

Nice article!
So does this means, React also supports 2 way data binding? The data component and view component can both change each other?