React Tutorial: Components, Hooks, and Performance.

WHAT IS REACT?
AND WHAT IS COMPONENTS, HOOKS, AND PERFORMANCE?

React is a JavaScript library for building for user interfaces built by Facebook. It’s also called as the view layer of web applications.

Components are the main part of the React as for human is heart, the heart is the main part to live likewise components in React. A component is a self-contained module that renders some output as well as we can write interface elements like a button or an input field as a React component. It might include one or more components in its output.

Kindly speaking, for writing the React apps we have to write React components that correspond the various interfaces and elements and after that organize these components inside higher-level components which define the structure of your application in React.

For instance, let take an example of the online form like as you fill much time for surveys or jobs and other purposes. A form consists of more than one element, like information/input fields, labels, as well as button and each element inside the form, is mention as a React component. We’d then write a higher-level component, the form component itself. The form component in React, would specify the structure of the form and include each of these elements inside it.

react


Meanwhile, each component in a React app has strict data management principles as well as it is a complex, interactive user interface often involve with complex data and application state.


TYPES OF REACT COMPONENTS

✔ Controlled and uncontrolled components:

In most of the applications, there is a need for input as well as some form of interaction with users, secondly, which allow them to type anything, upload the file, select fields, and so on. React deals with user interaction in two ways—controlled and uncontrolled components.

The controlled components by React which providing the value to an element that interacts with the user, whereas uncontrolled components don’t get the value property.

The function of Controlled Components that the developer has to run in the application is written below:

class ControlledInput extends React.Component {
 state = {
   value: ""
 };

 onChange = (e) => this.setState({ value: e.target.value });

 render() {
   return (
     <input value={this.state.value} onChange={this.onChange}/>
   );
 }
}


Secondly, the coding of uncontrolled components in the application is here:

class UncontrolledInput extends React.Component {
 input = React.createRef();

 getValue = () => {
   console.log(this.input.current.value);
 };

 render() {
   return (
     <input ref={this.input}/>
   );
 }
}

✔ Refs

In Refs the developer access to a React component or DOM element. It is considered as a good practice that, to try to avoid them and use them only in must-have scenarios though, they make the code a bit harder to read and break to-top-to-bottom data flow. Secondly, there are some cases where they are really necessary, on DOM elements. Also when attaching to the React component element, you can use methods from that component that you are referring to. But still, this practice sometimes avoided as there are better ways to deal with it.

➡ Three different ways of Refs:
  • Using a string literal,
  • Using callback function in the ref attribute,
  • Creating ref as React.createRef() and binding it to a class property as well as accessing it through it.

To build the application in React by Reference component below the code will help you to Run your application:

function withNewReference(Component) {
 class Hoc extends React.Component {
   render() {
     const {forwardedRef, ...props} = this.props;

     return <Component ref={forwardedRef} {...props}/>;
   }
 }

 return React.forwardRef((props, ref) => {
   return <Hoc {...props} forwardedRef={ref} />;
 });
}


✔ Error Boundaries:

Error boundaries are React components which catch the JavaScript errors from anywhere in their child component tree, as well as log those errors, and display in a fallback UI instead of the component tree. Secondly, error boundaries are catch errors during rendering, as well as below there is the code of error boundaries.

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    logToErrorLogger(error, info);
  }

  render() {
    if (this.state.hasError) {
      return <div>Help, something went wrong.</div>;
    }

    return this.props.children; 
  }
}


✔ Higher Order Components:

Higher Order Components (HOC) are often in React. They are a very popular pattern, one that developers easily used in their application. These components are just functions that take a component as an argument or will return a new component with extended capabilities as well as compared to the one without the higher order components wrapper.
Below here there is code to understand properly.

export function importantHoc() {
   return (Component) => class extends React.Component {
       importantFunction = () => {
           console.log("Very Important Function");
       };

       render() {
           return (
               <Component
                   {...this.props}
                   importantFunction={this.importantFunction}
               />
           );
       }
   };
}


HOOKS IN REACT

Hooks are functions that “hook into” React state as well as lifecycle features from function components and it doesn’t work inside classes, they just used to React without classes. They are most eagerly awaited addition to the React since the rewrite.


➡ Functions of hooks in React:

  • It allows the removal of a lot of components, so the code will look easier to read.
  • As well as enables you to use less code for the same effect.
  • Also makes functions way easier to think about as well as run.
  • It can also take parameters, also the result of one can be easily be used by another hook.
  • Minifies way better than classes because Minifies are more problematic to developers to use.
  • Even, remove Higher order components and render props patterns from your apps.
  • Also, capable of being custom-built by React developers.

Using effect Hook:

const fetchApi = async () => {
 const value = await fetch("https://jsonplaceholder.typicode.com/todos/1");
 console.log(await value.json());
};

export function Counter() {
 const [counter, setCounter] = useState(0);
 useEffect(() => {
   fetchApi();
 }, []);


 return (
   <div>
     {counter}
     <button onClick={() => setCounter(prevCounter => prevCounter + 1)}>+</button>
     <button onClick={() => setCounter(prevCounter => prevCounter - 1)}>-</button>
   </div>
 );
};

✔ Checking types

PropsTypes checks the properties (props) which received by a React component and checks the lines of the application. Whenever a different situation occurs like,  object instead of an array, it gives the console as well as It’s really important to note that PropTypes are only checked in development mode only, due to the impact on performance and the console warning.

➡ There is two popular option to check:

? TypeScript:
It is a type of upgrade version of JavaScript, developed by Microsoft, which can check errors before an app is even running as well as provides superior autocomplete function.
? Flow:
It is not a language as TypeScript but it’s a static type checker for JavaScript as well as it is more akin to a tool that includes in JavaScript than a language.


React Performance:

➡ There is a types of react performance:

⚡ Code Splitting: It can appear in one or more ways.
import ErrorBoundary from './ErrorBoundary';

const ComponentOne = React.lazy(() => import('./ComponentOne'));

function MyComponent() {
   return (
       <ErrorBoundary>
           <React.Suspense fallback={<div>Loading...</div>}>
               <ComponentOne/>
           </React.Suspense>
       </ErrorBoundary>
   );
}

Leave a Comment

Your email address will not be published. Required fields are marked *