Thursday, July 04, 2024

Efficiency of React Applications Through Props, State and Context Component Development

Before we dive into this interesting topic, let's recap what we learned in the previous lesson, which you can view here. We were introduced to JSX, JSX rendering, and created a simple React component, a Book List. We also explained the folder and file structure that React creates for you whenever you create a new React application. This wasn't explained in the first lesson, which you can view here; to avoid overwhelming you with too much information right alongside the necessary installation steps. However, through practical examples, React development is so straightforward that you might wonder what you were doing all these years without React components. Due to this simplicity, starting from this lesson, we will focus more on practice and coding with simple examples that will speed up your learning and understanding.

But we won't leave you without explanations of what you're using while creating amazing things in such simple ways. Efficiency is a key factor in React application development, and one of the most important elements influencing it are Props, State, and Context. These are the basic building blocks of React components. Understanding how each of these elements works and how to use them correctly can significantly improve your application's performance and maintainability. What you've learned so far in this tutorial can only bring you to this level of React. For the next level, you need data that will fill the structure of your React components. The next lesson in the React tutorial will introduce you to working with Hooks.

A developer learns the basic building blocks, Props, State and Context in the React library

A developer learns the basic building blocks, Props, State and Context in the React library

As we mentioned, the basic building blocks of React components are Props, State, and Context. When developing React applications, it is important to balance the use of Props, State, and Context to achieve optimal efficiency and maintainability. Too many Props can lead to unnecessary application load, while excessive use of State can result in performance loss. Context should be used where it is truly necessary, avoiding excessive complexity and code clutter. Ultimately, a proper understanding and use of Props, State, and Context will help you develop efficient and maintainable React applications that provide a fast and intuitive user experience.

  • Props – properties or attributes, sometimes called the same, are a way for React components to pass data to each other. Simply put, through Props, React components can communicate and share information, facilitating modularity and code reuse. However, care must be taken when passing large objects via Props, as this can lead to unnecessary application load and reduced performance. It is always advisable to pass only the necessary data via Props and avoid passing complex data structures when not required.
  • State – represents the internal status of a component that can change over time. Proper State management is crucial for efficiently managing the application state and reactively updating the user interface. However, excessive use of State can lead to excessive re-rendering of components and performance loss. Therefore, it is important to use State only where it is truly necessary and to avoid over-expanding it.
  • Context – is a mechanism that allows data to be shared between components in the component tree without the need to pass Props through every level. This can be useful when you want certain information to be available to all components within a specific part of the application, such as user information or theme settings. However, caution should be exercised when using Context, as overuse can lead to code clutter and reduced readability.

In this lesson, we will go through three practical examples that will illustrate each of the basic building blocks of React components in a practical way.

Props: How Do I Create a User Component That Passes Data?

Props - properties are data that are transferred from Parents to Children React components. Props are always immutable, which means that the data cannot be directly changed within the React component that receives it. They are used to pass data from higher component levels to lower levels, enabling communication between different parts of the application. Otherwise, Props are defined in the parent component and passed as arguments when rendering to the child component. The following example illustrates how it is coded and how it works. In the react_tutorial folder, create a new folder and name it lesson3. Position yourself in it and start Visual Studio Code with the following command.

manuel@manuel-virtual-machine:~/react_tutorial/lesson3$ code .

Open the Terminal Panel in Visual Studio Code. Type the following command.

manuel@manuel-virtual-machine:~/react_tutorial/lesson1$ npx create-react-app props

It takes about 6 minutes for the command to execute, so wait for that time for everything to install. In the public folder, find the index.html file and change the title HTML element.

<title>React Props</title>

Create a new folder in the src folder and call it components and in that folder create a new file and call it User.jsx. Note that the name of this file in practice usually has the first letter capitalized. In the User.jsx file, type the following JavaScript code.

import PropTypes from 'prop-types';

function User(props) {

    return(

        <div>

            <p>User: <strong> {props.user} </strong></p>

            <p>Status: <strong> {props.status} </strong></p>

            <p>Age: <strong> {props.age} </strong></p>

            <p>Premium: <strong> {props.isPremium ? "Yes" : "No"} </strong></p>

         </div>

    );  

}

// checks if pass values are correct data type

User.propTypes = {

    user: PropTypes.string,

    status: PropTypes.string,

    age: PropTypes.number,

    isPremium: PropTypes.bool,    

}

export default User

The first thing you should pay attention to in this code is the prop-types library. You can find it in the node_modules directory. It is a library in the React ecosystem that is used to check the types of type checking props that are passed to React components and is used as a plugin in the development of React applications. Through this library, you can also create default properties of forwarded data, but in our example we do it at the level of HTML elements. While you take type checking seriously, it's always done at the React component level as well because it makes it easier to find bugs. The User React component displays user information passed as Props. Each of the listed properties is used to display certain information about the user. In the src folder, click on the App.js file and change the content to the following.

import React, { useState } from 'react';

import User from './components/User';

function App() {

  const [statussetStatus= useState('');

  const [agesetAge= useState('');

  const [isPremiumsetIsPremium= useState(false);

  const [userNamesetUserName= useState('');

  const [userDatasetUserData= useState(null);

 

  const handleStatusChange = (event=> {

    setStatus(event.target.value);

  };

  const handleAgeChange = (event=> {

    setAge(event.target.value);

  };

  const handlePremiumChange = (event=> {

    setIsPremium(event.target.value === 'Yes');

  };

  const handleNameChange = (event=> {

    setUserName(event.target.value);

  };

  const handlePrintUserData = () => {

    setUserData({

      user: userName,

      status: status,

      age: age,

      isPremium: isPremium

    });

  };

  return (

    <div>

      <p><input

        type="text"

        value={userName}

        onChange={handleNameChange}

        placeholder="Enter User Name"

      /></p>

      <p><select value={status} onChange={handleStatusChange}>

        <option value="">Select Status</option>

        <option value="Professor">Professor</option>

        <option value="Student">Student</option>

        <option value="Guest">Guest</option>

      </select></p>

      <p><input

        type="number"

        value={age}

        onChange={handleAgeChange}

        placeholder="Enter Age"

      /></p>

      <div>

        <p><label>

          Premium:

          <input

            type="radio"

            value="Yes"

            checked={isPremium}

            onChange={handlePremiumChange}

          />

          Yes

        </label>

        <label>

          <input

            type="radio"

            value="No"

            checked={!isPremium}

            onChange={handlePremiumChange}

          />

          No

        </label></p>

      </div>

      <button onClick={handlePrintUserData}>Print Data</button>

      {userData && <User {...userData} />}

    </div>

  );

}

export default App;

This code might look complex for beginners, but if you simply extract the layout of the web page into the file index.html, it would be much shorter. Essentially, the code represents defining the state of the User React component. It also defines functions for handling changes. Remember that Props cannot change the values ​​passed to them in the React component. For example, don't confuse Props with props in the C# programming language. Then it also defines the function for displaying data by clicking the Print Data button. The rest is JSX rendering. When you execute this application, you will get results similar to the following image.

The result of React Props application

The result of React Props application

You can see what the coding of the previous application looks like in the following video.
 

React - 3. Props and User Component

State: How Do I Create a LikeDislikeCounter React Component That Counts Likes and Dislikes?

State - state is the internal data of a component that can evolve over time in response to user actions, events or changes in the application. It is mutable which, unlike a property, means that it can be changed directly within the component that owns it, usually through the setState function. It is used to store information that may change over time, such as user input, results of asynchronous calls, or any data that affects the UI. State is defined in the component's constructor and can be updated using the setState function, which automatically re-renders the component when the state changes. In the react_tutorial folder, open the lesson3 project in Visual Studio Code. And in the same project, create a new React application.

manuel@manuel-virtual-machine:~/react_tutorial/lesson3$ npx create-react-app props

In the public folder, find the index.html file and change the title HTML element.

<title>React - Like and Dislike Counter</title>

Create a new folder in the src folder and name it the same components and in that folder create a new file and name it LikeDislikeCounter.jsx Note that the name of this file in practice usually has the first letter capitalized. In the LikeDislikeCounter.jsx file, type the following JavaScript code.

import React, { useState } from 'react';

const LikeDislikeCounter = () => {

  const [likessetLikes= useState(0);

  const [dislikessetDislikes= useState(0);

 

  const incrementLikes = () => {

    setLikes(likes + 1);

  };

  const incrementDislikes = () => {

    setDislikes(dislikes + 1);

  };

  return (

    <div>

      <button onClick={incrementLikes}>Like</button>

      <span>&nbsp; Likes: <strong>{likes}</strong></span>&nbsp;&nbsp;

      <button onClick={incrementDislikes}>Dislike</button>

      <span>&nbsp; Dislikes: <strong>{dislikes}</strong></span>

    </div>

  );

};

export default LikeDislikeCounter;

 

In the preceding code, note the import of the React library and the useState function used to define the state of the React component. Next, the React component LikeDislikeCounter is defined, and both states of the LikeDislikeCounter React component are defined; likes and dislikes states that store the number of likes and dislikes until you refresh the web page. Then the functions that increment both the likes and dislikes counters are defined, i.e., increasing them by 1 when a particular Like or Dislike button is pressed. In the src folder, click on the App.js file and change the content to the following.

 

import React from 'react';

import LikeDislikeCounter from './components/LikeDislikeCounter';

const App = () => {

  return (

    <div>

      <h1>React Like and Dislike Counter</h1>

      <LikeDislikeCounter />

    </div>

  );

};

export default App;

This simple code represents the basic structure of a React application consisting of one main React component App and one sub component LikeDislikeCounter. The App React component displays a title and a LikeDislikeCounter component inside it, which allows the user to interactively use the like and dislike counter. When you execute this application, you will get results similar to the following image.

The result of React State application

The result of React State application

 You can see what the coding of the previous application looks like in the following video.

React - 4. State and Like-Dislike Counter Component

Context: How Do I Create a NavBar React Component That Uses a Button Component?

Context is another key concept in React that allows sharing data between React components located in different branches of the component tree, without having to pass Props - properties through each individual component. While Props are used to transfer data from the parent to the child component and while State represents the component's internal data that can change over time; Context is used to share data vertically across multiple levels of React components.

Context is especially useful when certain data is used in a large number of components within the application, because manually passing that data through Props becomes impractical and unclear. Typical examples of data that can be shared via Context include user information, application theme, language, authentication information, etc. In our example, we use Context to show you how to call the MyNavBar React component, which in turn calls the MyButton component. In the react_tutorial folder, open the lesson3 project in Visual Studio Code. And in the same project, create a new React application.

manuel@manuel-virtual-machine:~/react_tutorial/lesson3$ npx create-react-app mycontext

In the public folder, find the index.html file and change the title HTML element.

<title>React - Context</title>

Create a new folder in the src folder and name the same components and in that folder create new files and name the same MyNavBar.jsx and MyButton.jsx. In the LikeDislikeCounter.jsx file, type the following JavaScript code.

import React from "react";

import MyButton from "./MyButton";

function NavBar() {

    return (

        <div className="nav">

            <MyButton />

        </div>

    );

export default NavBar

This MyNavBar React component displays the app's navigation bar, which can contain various elements, but in this case, it only contains the MyButton component. This code shows how components can be used to organize and structure an application's user interface. In the MyButton React component, type the following JavaScript code.

import React, {useContextfrom 'react';

import { Context } from '../App';

function MyButton() {

    const [signedInsetSignedIn= useContext(Context);

    return (

        <button onClick={() => setSignedIn(!signedIn)}>

            {signedIn ? 'Sign out' : 'Sign in'}

    </button>

    );

}

export default MyButton

This React component uses Context to get information about whether the user is currently logged in or not, and allows them to log in or out by clicking a button. This demonstrates how context can be used to share data between components without having to pass Props through each level in the React component hierarchy. And in the App.js file, change the content to the following.

import React, { useState } from 'react';

import MyNavBar from './components/MyNavBar'

export const Context = React.createContext();

function App() {

  const [signedInsetSignedIn= useState(false)

  return ( 

    <div style={color: signedIn ? 'blue' : 'red' }}>

      <Context.Provider value={[signedInsetSignedIn]}>

          <MyNavBar />

          <h1>{signedIn ? "Signed in" : "Signed out"}</h1>

      </Context.Provider>

    </div>

  );

export default App;

This code shows how Context is used to share data; in this case, user login information between components within the application. The App React component sets the Context value and allows descendants to access that context and use that information. When you execute this application, you will get results similar to the following image.

The result of React MyContext application

The result of React MyContext application

You can see what the coding of the previous application looks like in the following video.

React - 5. Context and Navbar & Button Components


 


 

 

 

 

 

 

 

No comments:

Post a Comment