Understanding React Concepts part 3

React Component Composition

Component

Component is the basic building block of React. They are independent and reusable bits of code that accept props and return React elements. Understanding components and how to work with them is a must-know for every React developer.

//example component
const App () => {
  return (<p>"Hello World"</p>) //returns "Hello World"
}

Component Composition

This is a commonly used technique to make components more reusable and generic. It involves passing props from one component to the other. Props in this case could be objects, strings, numbers, or even other components. Some of the reasons for using component composition include:

  • Scalability: Creating components with composition in mind allows easy modification when new requirements arise.
  • Helps prevent prop drilling. Prop drilling involves passing props through multiple layers of components.
  • Reduces multiple re-rendering which in turn improves performance.
  • Good for handling scenarios where the component's children are not yet known.
//reusable component
const Tab ({ name, children }) => {
return(
  <h1> {name} </h1>
  <p> {children} </p>
  )
}

//container component
const App() => {
  return (
    <Tab  name="first">
      First Tab
    <Tab/>
  )
}

Imperative React

React is inherently declarative. This means it is driven by results rather than the step-by-step process of getting to that result. We make the declarations using JSX. JSX allows us to tell React WHAT to render and it is less concerned with HOW such rendering is achieved. Unlike React, JavaScript is imperative. In JavaScript, we write code that seems like a set of instructions explicitly outlining what we want the code to do. For example, say we want to render a paragraph tag inside a div tag in React and JavaScript:

//JavaScript
<html>
  <body>
    <div id="content">
    </div>
<script>
   var tag = document.createElement("p");
   var text = document.createTextNode("Hello World");
   tag.appendChild(text);
   var element = document.getElementById("content");
   element.appendChild(tag);
</script>
</body>
</html>

//React
const App = () => {
 return(
  <div>
    <p> Hello World </p>
  </div>
  )
}

Imperative Programming in React is usually wordy, so it makes sense why declarative programming is in use. Although, there are situations where we might need to use Imperative Programming in React. Some of these includes:

  • Implementing animations on a JSX element.
  • Getting an element's width or height via the DOM API.