Declarative vs Imperative Programming
April 18, 2021
What are they?
According to Wikipedia:
Declarative programming is a programming paradigm ⦠that expresses the logic of a computation without describing its control flow.
Imperative programming is a programming paradigm that uses statements that change a programās state.
In an easier-to-understand way:
Declarative Programming is like asking a food store owner to make you a cup of noodles. You donāt care how he does it, thatās up to him.
Imperative Programming is like asking the owner to make you a cup of noodles with the flavor you desired. You give him instructions to make a perfect cup for you.
Example
Here we just have a button that changes its color on click.
-
Imperative
const container = document.getElementById("container"); const btn = document.createElement("button"); btn.className = "btn red"; btn.onclick = function (event) { if (this.classList.contains("red")) { this.classList.remove("red"); this.classList.add("blue"); } else { this.classList.remove("blue"); this.classList.add("red"); } }; container.appendChild(btn); -
Declarative
class Button extends React.Component { this.state = { color: 'red' } handleChange = () => { const color = this.state.color === 'red' ? 'blue' : 'red'; this.setState({ color }); } render() { return ( <div> <button className={`btn ${this.state.color}`} onClick={this.handleChange} ></button> </div> ); } }
In both code snippets above, thereās the same logic that says if red then blue, but the React example never touches an element, it tells the element should be rendered with the current state and doesnāt actually manipulate the DOM.
When writing React, itās often good not to think of how you want to accomplish a result, but instead what the component should look like in its new state. This sets us up for a good control flow where the state goes through a series of predictable and replicable mutations.
Notes
- Avoid using Refs, sometimes itās necessary, but React team does not recommend it.
- Donāt manipulate the DOM directly.
- Communicating between siblings through props and use pure functional components (stateless) when possible.
Reference
https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2