DEV Community

Cover image for 10 Things you need to know in React.
Mohammad Sohrab Hossain
Mohammad Sohrab Hossain

Posted on

10 Things you need to know in React.

What is react?

React is an open source, front end, declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”.

Here are just few of the reasons why people choose to program with React.
Enter fullscreen mode Exit fullscreen mode
  1. React if fast. Apps made in React can handle complex updates and still feet quick and responsive.

  2. React is modular. Instead of writing large, dense files of code, you can write many smaller, reusable files. Reacts modularity can be a beautiful solution to JavaScript’s maintainability problems.

  3. React is scalable. Large programs that display a lot of changing data are where React performs best.

  4. React is flexible. You can use React for interesting projects that have nothing to do with making a web app. People are still figuring out Reacts potential.

  5. React is popular. While this reason has admittedly little to do with Reacts quality, the truth is that understanding React will make you more employable.
    What React Components?

Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML via a render () function.

Components come in two types
Enter fullscreen mode Exit fullscreen mode
  1. Class Components

  2. Function Components

    Class Components: A class component is a more featured way to define a React component. It also acts like a function that receives props, but that function also considers a private internal state as additional input that controls the returned JSX.

When creating a React component, the component’s name must start with an upper-case letter.

The component has to include the extends React. Component statement, this statement creates an inheritance to React. Component, and gives your component access to React. Component’s functions.

The component also requires a render () method, this method returns HTML.

Example: Create a Class components called Car

class Car extends React. Components {

render () {

return

Hi, I’m a Rolls Royce Car!

;

}

}

Now React application has a component called Car, which returns a

element.

To use this component in your application, use similar syntax as normal HTML:

Example: Display the Car component in the “root” element:

ReactDOM.render(, document.getElementById(‘root’));

Function Components: A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element. … Component and create a render function which returns a React element. This requires more code but will also give you some benefits which you will see later on.
Enter fullscreen mode Exit fullscreen mode

Here is the same example as above, but created using a Function component instead.

A Function component also returns HTML, and behaves pretty much the same way as a Class component, but Class components have some additions, and will be preferred in this tutorial.

Example: Create a Function component called Car

function Car () {return

Hi, I am also Rolls Royce Car!

;}

Once again, your React application has a Car component.

Refer to the Car component as normal HTML (except in React, components must start with an upper-case letter):

Example: Display the Car component in the "root" element:

ReactDOM.render(, document.getElementById('root'));

What are Props?

React is a component-based library which divides the UI into little reusable pieces. In some cases, those components need to communicate (send data to each other) and the way to pass data between components is by using props.

“Props” is a special keyword in React, which stands for properties and is being used for passing data from one component to another. But the important part here is that data with props are being passed in a uni-directional flow. (one way from parent to child)

Here are two important things about Props:

  1. Props are read-only.

  2. Props cannot be modified.

    Using Props in React: I will be explaining how to use Props step by step

  3. Firstly, define an attribute and its value(data).

  4. Then pass it to child components by using props.

  5. Finally, render the Props Data.

Example, we have a ParentComponent including another component (child):

class ParentComponent extends Component {

render () {

I’m the parent components.

);

}

}

And this is our ChildComponents:

const ChildComponents = () => {

return

I’m the 1st child!

};
What is state?

Answer: React components has a built-in state object. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders.

Here are two important things about State:

  1. State changes can be asynchronous.

  2. State can be modified using this.setState

ü Using State in React: I will be explaining how to use State step by step.

  1. We import useState Hook from React. It lets us keep local state in a function component.

  2. Inside the example components, we declare a new state variable by calling the useState Hook. It returns a pair of values, to which we give names.

  3. When the user clicks, we call setCount with a new value.

The State object can contain as many properties as you like:

Example: Specify all the properties your component need:

class Car extends React.Component {constructor(props) {super(props);this.state = {brand: "Ford",model: "Mustang",color: "red",year: 1964};}render() {return (

My Car

);}}

What is JSX?

JSX stands for JavaScript XML. JSX makes it easier to write and add HTML in React.

JSX allows us to write HTML in React.

JSX is an inline markup that looks like HTML and gets transformed to JavaScript. A JSX expression starts with an HTML-like open tag, and ends with the corresponding closing tag. JSX tags support the XML self-close syntax so you can optionally leave the closing tag off.

Coding JSX

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods.

JSX converts HTML tags into react elements.

Example:

With JSX:

const myelement =

I Love JSX!

;

ReactDOM.render(myelement, document.getElementById(‘root’));

Without JSX:

const myelement = React.createElement(‘h1’, {}, ‘I do not use JSX!’);

ReactDOM.render(myelement, document.getElementById(‘root’));
What is virtual DOM?

Virtual DOM is a virtual representation of the real DOM.

The virtual DOM then sends a batch update to the real DOM to update the UI. React uses virtual DOM to enhance its performance.

How does virtual DOM works?
Enter fullscreen mode Exit fullscreen mode

the Virtual DOM is a node tree that lists elements and their attributes and content as objects and properties. React’s render() method creates a node tree from React components and updates this tree in response to mutations in the data model, caused by actions.

htmlhead lang="en"bodyul class="list"li class="list__item""List item"

What is Optimizing performance in React?

Performance Optimization of a programs and software is the process modifying a software system to make it work more efficiently and execute more rapidly.

21 Performance Optimization Techniques for React Apps
Enter fullscreen mode Exit fullscreen mode
  1. Using Immutable Data Structures

  2. Function/Stateless Components and React.PureComponent

  3. Multiple Chunk Files

  4. Using Production Mode Flag in Webpack

  5. Dependency optimization

  6. Use React.Fragments to Avoid Additional HTML Element Wrappers

  7. Avoid Inline Function Definition in the Render Function.

  8. Throttling and Debouncing Event Action in JavaScript

  9. Avoid using Index as Key for map

  10. Avoiding Props in Initial States

  11. Spreading props on DOM elements

  12. Use Reselect in Redux to Avoid Frequent Re-render

  13. Avoid Async Initialization in componentWillMount()

  14. Memoize React Components

  15. CSS Animations Instead of JS Animations

  16. Using Web Workers for CPU Extensive Tasks

  17. Using a CDN

  18. Virtualize Long Lists

  19. Analyzing and Optimizing Your Webpack Bundle Bloat

  20. Consider Server-side Rendering

  21. Enable Gzip Compression on Web Server
    What is React Hook?

It allows you to use state and other React features without writing a class. Hooks are the functions which “hook into” React state and lifecycle features from function components. It does not work inside classes.

When to use Hook: If you write a function component, and then you want to add some state to it, previously you do this by converting it to a class. But now you can do it by using a Hook inside the existing function component.

Rules of Hook: Hooks are similar to JavaScript functions, but you need to follow these two rules when using them. Hook’s rule ensures that all the stateful logic in a component is visible in its source code. These rules are:

  1. Only call Hooks at the top level

Do not call Hooks inside loops, conditions, or nested functions. Hooks should always be used at the top level of the React functions. This rule ensures that Hooks are called in the same order each time a component render.

  1. Only call Hooks from React functions

You cannot call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Hooks can also be called from custom Hooks.

Pre requisites for React Hook

  1. Node version 6 or above

  2. NPM version 5.2 or above

  3. Create-react-app tool for running the React App
    What is Conditional Rendaring?

Conditional rendering is a term to describe the ability to render different user interface (UI) markup if a condition is true or false.
In React, it allows us to render different elements or components based on a condition.

7 Ways to Implement Conditional Rendering in React Applications
Enter fullscreen mode Exit fullscreen mode
  1. Using an if…else Statement
  2. Using a switch Statement
  3. Using Element Variables
  4. Using Ternary Operators
  5. Using Logical && (Short Circuit Evaluation)
  6. Using Immediately Invoked Function Expressions (IIFEs)
  7. Using Enhanced JSX Libraries Composition is the key

Parent components that own the state are often referred to as container components. They are responsible for state management and rendering children (this sounds so odd). Child components are used to trigger event handlers passed down from parents (like the InputBox component in previous examples) and to display the data.

Child components that are responsible for displaying the data are called presentational components.

Container component is often responsible for fetching data, API calls (see componentDidMount() lifecycle method) and so on. You should keep this in one place to avoid side-effects in presentational components. Those should be as dumb as possible about everything other than displaying the data.

This separation of concerns and terminology were popularized by Dan Abramov, the author of Redux. You can read more about it in his article.

You can see that it all fits together. When every component follows single responsibility principle it can be composed with others and reused.

The biggest challenge is to figure out how to divide those responsibilities and where to put the state. If you want to know more about the topic search for “thinking in react” articles.

Top comments (1)

Collapse
 
saroj990 profile image
saroj sasmal

Hi there, quick tip! do use language markup so that code doesn't get mixed up with text.

dev.to/hoverbaum/how-to-add-code-h...