Principles of React

Before we start learning about React Hooks, we are going to learn about the three fundamental principles of React. These principles allow us to easily write scalable web applications. The fundamental principles are important to know, as they will help us to understand how and why Hooks fit into the React ecosystem.

React is based on three fundamental principles:

  • Declarative: Instead of telling React how to do things, we tell it what we want it to do. As a result, we can easily design our applications and React will efficiently update and render just the right components when the data changes. For example, the following code, which duplicates strings in an array is imperative, which is the opposite of declarative:
const input = ['a', 'b', 'c']
let result = []
for (let i = 0; i < input.length; i++) {
result.push(input[i] + input[i])
}
console.log(result) // prints: [ 'aa', 'bb', 'cc' ]

As we can see, in imperative code, we need to tell the computer exactly what to do, step by step. However, with declarative code, we can simply tell the computer what we want, as follows:

const input = ['a', 'b', 'c']
let result = input.map(str => str + str)
console.log(result) // prints: [ 'aa', 'bb', 'cc' ]

In the previous declarative code, we tell the computer that we want to map each element of the input array from str to str + str. As we can see, declarative code is much more concise.

  • Component-based: React encapsulates components that manage their own state and views, and then allows us to compose them in order to create complex user interfaces.
  • Learn once, write anywhere: React does not make assumptions about your technology stack, and tries to ensure that you can develop apps without rewriting existing code as much as possible.

We just mentioned that React is component-based. In React, there are two types of components:

  • Function components: JavaScript functions that take the props as an argument, and return the user interface (usually via JSX)
  • Class components: JavaScript classes that provide a render method, which returns the user interface (usually via JSX)

While function components are easier to define and understand, class components were needed to deal with state, contexts, and many more of React's advanced features. However, with React Hooks, we can deal with React's advanced features without needing a class component!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.23.30