Skip to main content

Getting Started with React and Vite

ยท 7 min read

Getting Started with React and Vite

Vite is a modern build tool that offers faster development times and optimized builds. It aligns with modern web standards and provides out-of-the-box support for TypeScript, making it an excellent choice for React development. In this blog post, we will learn how to get started with React by creating a new app using Vite. We will follow the steps to set up our development environment and build our first React application.

Quick Startโ€‹

To get started with Vite, we need to have Node.js installed on our system. We can install Node.js by downloading the installer from the official website or using a package manager. Once we have Node.js installed, we can use npm to create a new Vite project with the React template.

To quickly get started with Vite and React, follow these steps:

npm create vite@latest my-app --template react

This command will create a new Vite project called my-app using the React template. It will set up the project structure and install the necessary dependencies. We can then navigate to the my-app directory and start the development server to see our new React application in action.

Now navigate to the my-app directory:

cd my-app

if you prefer using npm:

npm install

Or, if you prefer using yarn:

yarn

Now start the development server:

npm start

Or, if you prefer using yarn:

yarn start

Once the development server has started, open http://localhost:3000/ in your browser to see your new React application. You can start building your React components, defining routes, and managing state using the React Context API.

Project Structureโ€‹

The Vite project structure for a new React application is minimal and easy to understand. It provides a clean and organized layout that aligns with modern web development practices. Here is an overview of the project structure:

my-app
โ”œโ”€โ”€ node_modules
โ”œโ”€โ”€ public
โ”‚ โ”œโ”€โ”€ favicon.ico
โ”‚ โ”œโ”€โ”€ index.html
โ”œโ”€โ”€ src
โ”‚ โ”œโ”€โ”€ App.css
โ”‚ โ”œโ”€โ”€ App.jsx
โ”‚ โ”œโ”€โ”€ index.css
โ”‚ โ”œโ”€โ”€ index.jsx
โ”œโ”€โ”€ .gitignore
โ”œโ”€โ”€ package.json
โ”œโ”€โ”€ README.md

The public directory contains the static assets for our application, such as the index.html file and the favicon.ico icon. The src directory contains the source code for our React application, including the main index.jsx file and the App.jsx component.

Building Our First React Applicationโ€‹

Now that we have our development environment set up and our project structure in place, we can start building our first React application. We can create new components, define routes, and manage state using the React Context API. We can also use popular libraries such as React Router and React hooks to enhance our application.

To learn more about building React applications with Vite, refer to the official React documentation. The documentation provides detailed information on React concepts, best practices, and advanced topics.

Why Vite?โ€‹

Vite offers several advantages for React development, including:

  • Faster Development: Vite provides a lightning-fast development server with hot module replacement (HMR) and instant server start. It eliminates the need for a bundler during development, resulting in faster build times and a smoother development experience.
  • Optimized Builds: Vite optimizes the production build by leveraging native ES module support in modern browsers. It generates highly optimized and tree-shaken builds, resulting in smaller bundle sizes and improved performance.
  • Modern Web Standards: Vite aligns with modern web standards and leverages native browser features such as ES modules, dynamic imports, and web workers. It provides an efficient development environment that embraces the latest web technologies.
  • TypeScript Support: Vite offers out-of-the-box support for TypeScript, enabling us to write type-safe code and leverage advanced TypeScript features. It provides seamless integration with React and TypeScript, making it an excellent choice for React development.
  • Plugin Ecosystem: Vite has a rich plugin ecosystem that allows us to extend its functionality and customize the build process. We can use plugins to add features such as CSS preprocessing, asset optimization, and code transformation.
  • Developer Experience: Vite provides an excellent developer experience with features such as instant server start, optimized builds, and real-time feedback. It streamlines the development workflow and enables us to focus on building great React applications.
  • Community Support: Vite has a growing community and active maintainers who contribute to its development and provide support. It has gained popularity in the React ecosystem and is widely adopted by developers.
  • Migration Path: Vite offers a smooth migration path for existing React projects by providing a Vite-compatible React template. It allows us to migrate our projects to Vite without significant changes to the codebase.
  • Future Compatibility: Vite is designed to be future-compatible and aligns with the latest web standards and best practices. It provides a solid foundation for building modern React applications that are ready for the future.
  • Open Source: Vite is an open-source project with a permissive license that allows us to use, modify, and distribute it freely. It is developed in the open and welcomes contributions from the community.
  • Continuous Improvement: Vite is continuously improved and updated with new features, optimizations, and bug fixes. It has a roadmap for future releases and aims to provide a cutting-edge development experience for React developers.
  • Integration with Vercel: Vite has seamless integration with Vercel, a popular platform for deploying web applications. It allows us to deploy our Vite projects to Vercel with minimal configuration and take advantage of Vercel's features such as serverless functions and edge caching.
  • Developer Tools: Vite provides a set of developer tools that enhance the development experience, including a built-in development server, optimized builds, and real-time feedback. It offers a comprehensive toolkit for building and debugging React applications.
  • Performance Optimization: Vite optimizes the development and production builds by leveraging modern web standards and best practices. It provides a performant and efficient build process that results in faster load times and improved user experience.
  • Community Plugins: Vite has a rich ecosystem of community plugins that extend its functionality and provide additional features. We can use plugins to add support for features such as PWA, internationalization, and analytics to our Vite projects.
  • Learning Resources: Vite has a growing collection of learning resources, tutorials, and documentation that help developers get started with Vite and build great React applications. It provides comprehensive guidance on using Vite effectively and efficiently.
  • Developer Community: Vite has a vibrant developer community that actively contributes to its development and provides support to fellow developers. It has a dedicated Discord server, GitHub repository, and community forums where developers can connect and collaborate.
๐Ÿ“š Learn More:

To learn more about Vite, visit the official Vite documentation.

Conclusionโ€‹

In this blog post, we learned how to get started with React by creating a new app using Vite. We followed the steps to set up our development environment and build our first React application. We explored the advantages of using Vite for React development and discussed its features, benefits, and community support. We also learned about the project structure of a new React application created with Vite and how to build our first React application. We hope this blog post has provided you with valuable insights into using Vite for React development and has inspired you to explore the possibilities of building modern web applications with Vite and React.

Git Best Practices: Commit Often, Perfect Later, Publish Once

ยท 5 min read

Git is a powerful tool for managing the development of software projects, but it can be challenging to use effectively. In this article, we'll take a look at some best practices for using Git, including how to structure your commits, how to manage branches, and how to collaborate with others. By following these best practices, you can make your development process more efficient and less error-prone.

Commit Often, Perfect Later, Publish Onceโ€‹

One of the most important best practices for using Git is to commit your changes often. This means that you should make small, focused commits that capture a single logical change to your code. By committing often, you can keep a detailed history of your changes, which makes it easier to understand the evolution of your codebase and to track down bugs.

When you're working on a new feature or fixing a bug, it's important to commit your changes frequently, even if they're not perfect. You can always go back and revise your commits later to clean them up and make them more coherent. By committing often and revising later, you can avoid the temptation to make large, sweeping changes to your code all at once, which can lead to confusion and errors.

Once you're satisfied with your changes, you can publish them to a shared repository, such as GitHub or Bitbucket. By publishing your changes once, you can make it easier for others to review your work and to collaborate with you. This can help to prevent merge conflicts and to ensure that everyone is working from the most up-to-date version of the codebase.

Structure Your Commitsโ€‹

When you're committing your changes, it's important to structure your commits in a way that makes it easy to understand the evolution of your codebase. This means that you should avoid making large, monolithic commits that capture multiple unrelated changes. Instead, you should make small, focused commits that capture a single logical change to your code.

One way to structure your commits is to use the "atomic commit" pattern, which involves making a series of small, focused commits that capture a single logical change to your code. For example, if you're working on a new feature, you might make a series of commits that add individual components of the feature, such as the user interface, the business logic, and the data model. By structuring your commits in this way, you can make it easier to understand the evolution of your codebase and to track down bugs.

Another way to structure your commits is to use the "semantic commit" pattern, which involves using a standardized format for your commit messages. For example, you might use a format like "feat: add new feature" or "fix: correct bug in user interface". By using a standardized format for your commit messages, you can make it easier to understand the purpose of each commit and to navigate through the history of your codebase.

Manage Your Branchesโ€‹

When you're working on a software project, it's important to manage your branches effectively. This means that you should create a new branch for each new feature or bug fix that you're working on, and that you should merge your branches back into the main codebase once you're finished with them.

By managing your branches effectively, you can make it easier to collaborate with others and to keep your codebase organized. For example, if you're working on a new feature, you might create a new branch for the feature, make your changes on the branch, and then merge the branch back into the main codebase once the feature is complete. By doing this, you can make it easier for others to review your work and to collaborate with you, and you can avoid introducing bugs and conflicts into the main codebase.

Collaborate with Othersโ€‹

One of the most powerful features of Git is its ability to help you collaborate with others. By using Git, you can make it easier to share your work with others, to review their work, and to resolve conflicts and merge changes together.

When you're collaborating with others, it's important to communicate effectively and to follow best practices for using Git. For example, you should make sure to pull the latest changes from the shared repository before you start working on a new feature or bug fix, and you should make sure to push your changes to the shared repository once you're finished with them. By following these best practices, you can make it easier to collaborate with others and to keep your codebase organized and up-to-date.

Conclusionโ€‹

Git is a powerful tool for managing the development of software projects, but it can be challenging to use effectively. By following best practices for using Git, such as committing often, structuring your commits, managing your branches, and collaborating with others, you can make your development process more efficient and less error-prone. By doing this, you can make it easier to understand the evolution of your codebase, to track down bugs, and to collaborate with others. Happy coding!

Sed: Normalize markdown file with Regex

ยท 3 min read
Ajay Dhangar

I have been using web clipper to save articles and blog posts for a while now. It's a great tool to save content from the web and organize it in a clean and readable format. However, the markdown files generated by web clipper are not always consistent, and I often find myself manually editing them to make them more readable.

One of the common issues I encounter is inconsistent formatting of the front matter in the markdown files. The front matter is a block of metadata at the beginning of a markdown file that contains information such as the title, author, tags, date, and description of the content. Here's an example of what the front matter looks like:

---
title: 'Sed: Normalize markdown file with Regex'
author: Ajay Dhangar
tags: [sed, regex, web clipper]
date: 2020-11-26 21:13:28
description: How to normalize markdown file with Regex
draft: false
---

As you can see, the front matter is enclosed in three dashes (---) at the beginning and end of the block, and each key-value pair is separated by a colon (:). The keys and values are also enclosed in single quotes (') to ensure that special characters are escaped properly.

To make the front matter consistent across all my markdown files, I decided to use the sed command-line utility to write a simple regular expression that would normalize the front matter. Here's the regular expression I came up with:

sed -i -E "s/^---\n(.*: .*\n)+---\n//g" file.md

Let's break down the regular expression:

  • ^---\n matches the opening three dashes at the beginning of the file, followed by a newline character.
  • (.*: .*\n)+ matches one or more lines containing a key-value pair, where the key is followed by a colon and a space, and the value is followed by a newline character.
  • ---\n matches the closing three dashes at the end of the block, followed by a newline character.
  • /g is a flag that tells sed to perform the substitution globally, i.e., on all matching lines in the file.

When I run this command on a markdown file, it removes the existing front matter and leaves me with just the content of the file. This is exactly what I want, as I can then manually add a consistent front matter to the file.

I hope this example gives you an idea of how powerful regular expressions can be when used with command-line utilities like sed. With a little bit of practice, you can write regular expressions to perform complex text manipulations with ease. If you're interested in learning more about regular expressions, I highly recommend checking out the RegexOne interactive tutorial, which is a great resource for beginners.

nvs: One Node Version Per Terminal in Windows

ยท One min read

nvs is a cross-platform Node.js version manager that allows you to install and use multiple versions of Node.js on the same machine. It is similar to nvm for Unix-based systems. nvs is a simple and easy-to-use tool that allows you to switch between different versions of Node.js with a single command.

In this article, we will learn how to install and set up nvs on Windows for PowerShell and Git-Bash.

CI evolution: From FTP client to GitHub Action

ยท 3 min read
Ajay Dhangar

In the early days of web development, the most common way to deploy a website was to use an FTP client. This involved manually uploading files to a remote server, which was a time-consuming and error-prone process. As web development practices evolved, so did the tools and techniques for deploying websites. One of the most significant advancements in this area has been the introduction of continuous integration (CI) and continuous deployment (CD) pipelines, which automate the process of building and deploying web applications.

In this article, we'll take a look at the evolution of remote file management, from the use of FTP clients to the adoption of GitHub Actions for automated deployment.

The FTP client eraโ€‹

In the early days of web development, the most common way to deploy a website was to use an FTP client. This involved manually uploading files to a remote server, which was a time-consuming and error-prone process. Developers would typically make changes to their local files, then use an FTP client to upload those changes to the server. This process was often slow and cumbersome, and it was easy to make mistakes that could result in broken websites.

The rise of CI/CD pipelinesโ€‹

As web development practices evolved, so did the tools and techniques for deploying websites. One of the most significant advancements in this area has been the introduction of continuous integration (CI) and continuous deployment (CD) pipelines. CI/CD pipelines automate the process of building and deploying web applications, making it faster, more reliable, and less error-prone than manual deployment methods.

GitHub Actions for automated deploymentโ€‹

One of the most popular CI/CD solutions for web development is GitHub Actions. GitHub Actions is a powerful, flexible, and easy-to-use tool for automating the build, test, and deployment processes of web applications. With GitHub Actions, you can define custom workflows that automatically build and deploy your web applications whenever you push changes to your repository. This makes it easy to ensure that your websites are always up-to-date and error-free, without the need for manual intervention.

Conclusionโ€‹

The evolution of remote file management has come a long way since the days of using FTP clients to manually upload files to remote servers. With the introduction of CI/CD pipelines and tools like GitHub Actions, web developers now have powerful, automated solutions for building and deploying web applications. These tools make it faster, easier, and more reliable to deploy websites, and they help ensure that your websites are always up-to-date and error-free. If you're still using an FTP client to deploy your websites, it's time to consider upgrading to a more modern, automated solution like GitHub Actions.

Install MongoDB Windows

ยท 3 min read

MongoDB is a popular NoSQL database that is known for its flexibility and scalability. It is widely used in modern web applications and is a great choice for storing and managing large volumes of data. In this article, we will walk you through the process of installing MongoDB on a Windows system.

Step 1: Download the MongoDB Installerโ€‹

The first step is to download the MongoDB installer from the official MongoDB website. You can find the installer at the following URL: https://www.mongodb.com/try/download/community

Step 2: Run the MongoDB Installerโ€‹

Once the installer has been downloaded, you can run it to start the installation process. Follow the on-screen instructions to complete the installation. You can choose the "Complete" setup type to install all the MongoDB tools, including the MongoDB shell (mongosh).

Step 3: Add MongoDB to the System Pathโ€‹

After the installation is complete, you need to add the MongoDB binaries to your system's PATH environment variable. This will allow you to run MongoDB and mongosh commands from any directory in your terminal.

To add MongoDB to the system PATH, follow these steps:

  1. Open the Control Panel and navigate to "System and Security" > "System" > "Advanced system settings".
  2. In the System Properties window, click on the "Environment Variables" button.
  3. In the Environment Variables window, select the "Path" variable under "System variables" and click the "Edit" button.
  4. Click the "New" button and add the path to the "bin" directory of your MongoDB installation (e.g., C:\Program Files\MongoDB\Server\5.0\bin).
  5. Click "OK" to save the changes and close the Environment Variables window.
  6. Click "OK" again to close the System Properties window.
  7. Restart your terminal to apply the changes.
  8. You can now run MongoDB and mongosh commands from any directory in your terminal.
  9. To verify that MongoDB and mongosh are installed correctly, you can run the following commands in your terminal:
mongod --version
mongosh --version

Step 4: Start the MongoDB Serviceโ€‹

To start the MongoDB service, you can run the following command in your terminal:

mongod

This will start the MongoDB server on your local machine. You can now connect to the MongoDB server using the mongosh shell.

Step 5: Connect to the MongoDB Serverโ€‹

To connect to the MongoDB server, you can run the following command in your terminal:

mongosh

This will open the mongosh shell, and you can start interacting with the MongoDB server using JavaScript-like syntax.

Congratulations! You have successfully installed MongoDB and mongosh on your Windows system. You are now ready to start building powerful applications with MongoDB as your database. Happy coding!

Install MongoDB Linux

ยท 2 min read

MongoDB is a popular NoSQL database that is known for its flexibility and scalability. It is widely used in modern web applications and is a great choice for storing and managing large volumes of data. In this article, we will walk you through the process of installing MongoDB on a Linux system, specifically Debian Bullseye.

Step 1: Import the MongoDB GPG Keyโ€‹

The first step is to import the MongoDB GPG key, which is used to verify the authenticity of the MongoDB packages. You can do this by running the following command in your terminal:

wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -

Step 2: Create a MongoDB Source List Fileโ€‹

Next, you need to create a source list file for MongoDB. You can do this by running the following command:

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/debian bullseye/mongodb-org/5.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

Step 3: Update the Package Databaseโ€‹

After creating the source list file, you need to update the package database to include the MongoDB repository. You can do this by running the following command:

sudo apt update

Step 4: Install MongoDBโ€‹

Now that the MongoDB repository has been added to your package database, you can install MongoDB by running the following command:

sudo apt install -y mongodb-org

Step 5: Start the MongoDB Serviceโ€‹

Once MongoDB is installed, you can start the MongoDB service by running the following command:

sudo systemctl start mongod

You can also enable the MongoDB service to start automatically at boot time by running the following command:

sudo systemctl enable mongod

Step 6: Verify the MongoDB Installationโ€‹

To verify that MongoDB has been installed successfully, you can run the following command to check the status of the MongoDB service:

sudo systemctl status mongod

You should see output indicating that the MongoDB service is active and running.

Step 7: Install mongoshโ€‹

Finally, you can install mongosh, the official MongoDB shell, by running the following command:

sudo apt install -y mongosh

Conclusionโ€‹

Congratulations! You have successfully installed MongoDB and mongosh on your Debian Bullseye system. You can now start using MongoDB to store and manage your data. If you have any questions or run into any issues, feel free to consult the official MongoDB documentation. Happy coding!

Step-by-Step Guide Debugging Tests in Create React App

ยท 3 min read

Debugging tests in a React application can be challenging, but fear not! We've got you covered with this step-by-step guide to help you overcome the common hurdles and make your tests shine. Let's dive in:

Step 1: Install Create React App

If you haven't already set up your Create React App project, start by installing it:

npx create-react-app my-app
cd my-app

Step 2: Writing a Test

Create a simple React component (e.g., a Button) in a separate file and write a test for it. For example:

src/Button.js
import React from 'react';

const Button = () => {
return <button>Click Me</button>;
};

export default Button;
src/Button.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import Button from './Button';

test('renders the button', () => {
render(<Button />);
const buttonElement = screen.getByText('Click Me');
expect(buttonElement).toBeInTheDocument();
});

Step 3: Run the Tests

Execute the tests using the following command:

npm test

Step 4: Spotting the Failure

If the test fails, don't panic! First, identify the failing test case.

Step 5: Reproduce the Failure Locally

Make sure the failure occurs consistently by reproducing it locally. Ensure that you're running the correct test files and dependencies.

Step 6: Debugging Techniques

Now, let's employ some debugging techniques to resolve the issue:

6.1. Use console.log

Place console.log statements at different points in your test to check the values of variables or components. For example:

test('renders the button', () => {
render(<Button />);
console.log(screen.getByRole('button').outerHTML);
const buttonElement = screen.getByText('Click Me');
console.log(buttonElement); // Check the button element in the console
expect(buttonElement).toBeInTheDocument();
});

6.2. Utilize debugger

You can use the debugger keyword to pause test execution at a specific point. Open your browser's developer tools to inspect variables and the call stack. For example:

test('renders the button', () => {
render(<Button />);
debugger; // Execution will pause here, and you can inspect the app and test code.
const buttonElement = screen.getByText('Click Me');
expect(buttonElement).toBeInTheDocument();
});

6.3. Inspect with Chrome DevTools

Open your app in Chrome, right-click, and select "Inspect." Navigate to the "Console" tab to interactively debug your tests using the same tools you use for your regular app.

6.4. Snapshot Testing

If you suspect issues with rendering, consider using snapshot testing. Jest can generate snapshots of your components and compare them for changes. Learn more about snapshot testing in the official documentation.

Step 7: Fix the Test

Based on your observations during debugging, fix the failing test case. It might involve modifying the component or adjusting your expectations in the test.

Step 8: Rerun the Tests

After making changes, run the tests again to ensure everything is working correctly:

npm test

Step 9: Celebrate Success!

Congratulations! You've successfully debugged your test and conquered the Bug Monsters. Repeat these steps whenever you encounter testing issues in your React applications.

Prompt Engineering Guide

ยท 2 min read

Prompt Engineering is a process of creating a prompt that is used to guide the user through a series of steps to achieve a specific goal. It is a powerful tool that can help users complete complex tasks with ease and efficiency. In this guide, we will walk you through the process of creating an effective prompt that will help you achieve your desired outcome.

Step 1: Define the Goalโ€‹

The first step in creating an effective prompt is to define the goal you want to achieve. This could be anything from completing a task, learning a new skill, or solving a problem. By clearly defining the goal, you can create a prompt that guides the user towards that goal.

Step 2: Identify the Stepsโ€‹

Once you have defined the goal, the next step is to identify the steps required to achieve that goal. Break down the goal into smaller, manageable steps that the user can follow to reach the desired outcome. This will help the user understand what they need to do and how to do it.

Step 3: Design the Promptโ€‹

With the goal and steps identified, it's time to design the prompt. The prompt should be clear, concise, and easy to follow. Use simple language and provide clear instructions to guide the user through each step. You can use visual cues, such as arrows or icons, to help the user navigate the prompt.

Step 4: Test the Promptโ€‹

Before deploying the prompt, it's essential to test it to ensure that it works as intended. Test the prompt with a small group of users to gather feedback and identify any issues or areas for improvement. Make any necessary adjustments based on the feedback received.

Step 5: Deploy the Promptโ€‹

Once you have tested the prompt and made any necessary adjustments, it's time to deploy it. Make the prompt available to users and monitor its performance. Collect data on how users interact with the prompt and use this information to make further improvements.

Conclusionโ€‹

Creating an effective prompt is a valuable skill that can help you guide users through complex tasks and achieve your desired outcomes. By following these steps, you can create a prompt that is clear, concise, and easy to follow, helping users complete tasks with ease and efficiency. Happy prompting!