Understanding React Concepts part 2

Destructuring In React

Destructuring is a method in Javascript that is used to make our codes cleaner and more readable. It is a way to get data from arrays and objects much better and with fewer lines of code. Working with arrays and objects is part of the everyday life of a react developer so it is important to understand destructuring because it makes our code more concise.

Object Destructuring

Object Destructuring is commonly used as it enables us to access multiple properties of an object with a single line of code, making it more readable.

const car = {
brand: 'Mercedes',
owner: 'Paul',
};

// without object destructuring
const brand = car.brand;
const owner = car.owner;

// with object destructuring
const { brand, owner } = car;

In react, we make use of props to pass data throughout the component tree. Since props are objects containing data that can be passed from component to component, it makes sense to destructure them as it makes passing them more convenient.

//App Component
const App = () => {
  const name = "Paul";
  const gender = "male";
  return (<Child name={name} gender={gender} />)
}

// without destructuring
const Child = (prop) => {
 const name = prop.name;
 const gender = prop.child;
 return (
    <p>{name} {gender}</p>
)
}

// with destructuring
const Child = ({name, gender}) => {
 return (
    <p>{name} {gender}</p>
)
}

React Side Effects

Side Effects are unpredictable actions that are performed with the "outside world"(outside of React's domain). We refer to side effects as unpredictable because they do not provide predictable outputs like most React Components. React Components receive inputs(props) and provide a predictable output of jsx. Most applications require side effects in one way or the other to function effectively. Some common side effects include:

  1. Sending requests to get data from a backend server.
  2. Interaction with browser APIs e.g local storage.

To handle the usage of side effects in our React applications, we make use of the useEffect hooks. The useEffect hook helps prevent rendering issues that might occur when making use of side effects in our applications

Rendering Multiple Top-level Elements

In react, we can only have a single top-level element that is then wrapped around the rest of our jsx code. We can work around this by wrapping our jsx into an array.

const User = () => [
    <p>My name is Paul</p>
    <p>I am a boy</p>
]

While this is a valid way to render multiple top-level elements, it can become very unreadable depending on the jsx being rendered. Another way to go about this is to make use of React Fragments. This wraps other elements into a single top-level element without adding to the rendered output. This means it does not bring in new elements into our rendered HTML.

const User = () => {
    <>
        <p>My name is Paul</p>
        <p>I am a boy</p>    
    </>
};