This content originally appeared on DEV Community and was authored by Marcin Zielinski
When you go to React.js front page you can read that:
Declarative.
React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.
Then you look at a simple component:
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
And start to wonder how this code can be considered declarative? Is there any truth in the description? Let's find out.
We'll begin with the most well known declarative language: CSS. Some love it, most people hate it but everybody agrees that it's declarative.
This CSS code:
.trendy { color: red }
.fancy { color: blue }
can be translated to pseudocode:
when element class is `trendy` its text color should be red
when element class is `fancy` its text color should be blue
React expects similar declarative view description from you:
when component state is `1` then the view should be <div>1</div>
when component state is `2` then the view should be <div>2</div>
...
The format of the view description that React uses is commonly known as VDOM and looks like this: { type: "div", props: {...} }. That's what JSX evaluates to.
Okay, the code it declarative but it isn't manageable (writing a clause for every possible number, yuck).
Can we do better? How about this code:
when component state is `n` then the view should be <div>{n}</div>
With just a single line of pseudocode we have all the numbers covered. This code is still declarative - it's equivalent to the previous pseudocode.
In CSS you can encounter special kind of declarations that are applied based on some data, like the position of an element. So instead of writing:
div:nth-child(1) { color: gray; }
div:nth-child(3) { color: gray; }
div:nth-child(5) { color: gray; }
...
You can write:
div:nth-child(odd) { color: gray; }
Is there something similar in the React world? Well, yes. It's your old pal, Mr. Component:
function Component({ n }) {
return <div>{ n }</div>
}
It's a declarative function that describes the relation between the state and the view. So indeed, this is a declarative code. Whenever React needs to know how the current view should look like it fires up Component.
There you have it: React components are just like sophisticated CSS declarations.
This content originally appeared on DEV Community and was authored by Marcin Zielinski
Marcin Zielinski | Sciencx (2021-08-26T17:41:30+00:00) What “declarative” means in React. Retrieved from https://www.scien.cx/2021/08/26/what-declarative-means-in-react/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.