useEffect Usecase: Run Side Effect Only Once After Initial Render

Side Effect Runs Only Once After Initial Render You may want to run the side effect just once after the initial render. A typical case will be fetching data making an API call, and storing the response in the state variable after the initial render. You do not want to make this API call again. You can pass an empty array as the second argument to the useEffect hook to tackle this use case....

January 10, 2023 · 1 min · Daman Arora

What Are Side Effects in React and How to Handle Them Effectively

In essence, a react component consists of a function that executes from top to bottom and handles bringing something onto the screen or responding to user input, such as clicking. Whether you use state or other functions in such a function, everything in a component is concerned with bringing something to the screen. A side effect is anything else that occurs within an application. For example, sending an HTTP request or storing something in the browser’s storage....

January 10, 2023 · 2 min · Daman Arora

Write Semantically Better React Code

Using Fragments to solve the problem of </div> Soup When writing a component in React, you can’t have more than one root JSX element. So if you return a value or if you store a value in a variable, that value must only be exactly one JSX element not two or three or four side by side adjacent elements. Due to which, you have to wrap a <div> around all the elements in the return statement, this technically make the return statement to return only one value as a whole....

January 9, 2023 · 1 min · Daman Arora

Three Major Ways to Style a React Component

Inline CSS This is the CSS styling sent to the element directly using the HTML or JSX. You can include a JavaScript object for CSS in React components, although there are a few restrictions such as camel casing any property names which contain a hyphen. Example: import React from "react"; const spanStyles = { color: "#fff", borderColor: "#00f" }; const Button = props => ( <button style={{ color: "#fff", borderColor: "#00f" }}> <span style={spanStyles}>Button Name</span> </button> ); Styled-Components Styled-components is a library that utilizes tagged template literals — which contain actual CSS code between two backticks — to style your components....

January 1, 2023 · 2 min · Daman Arora

Using a List to Render Multiple React Components

You can build collections of elements and include them in JSX using curly braces {}. Below, we loop through the numbers array using the JavaScript map() function. We return a <li> element for each item. Finally, we assign the resulting array of elements to listItems: const numbers = [1, 2, 3, 4, 5]; const listItems = numbers.map((number) => <li>{number}</li> ); Then, we can include the entire listItems array inside a <ul> element:...

January 1, 2023 · 2 min · Daman Arora