React: Busted Myths and How to avoid pitfalls
spread-operator
myths
react
frontend-developer

React.js Myth Busted

In the world of software development, there are often strongly held beliefs and practices that can become ingrained in certain communities. React, a popular JavaScript library for building user interfaces, is no exception. In this blog post, we’ll delve into some of the common misconceptions and rigid beliefs that some React developers hold, and why they can hinder your ability to write good React code.

Breaking Down the React Cult Controversies

I have identified several areas where React developers may fall prey to these “cults”:

  1. The Cult of the Never Spreaders
  • Belief: Spreading operators should never be used in React because they are bad for performance.
  • Reality: Spreading is a common way to create new arrays or objects in React. While it does create new references, this is often necessary to signal to React that the data has changed.
  • Verdict: 2 out of 5. Spreading can be misused, but it’s a valid technique in most cases.

2. The cult where Redux is Mandatory

  • Belief: Every React application needs a state management library like Redux.
  • Reality: React hooks, Context API, and other built-in features can handle state management for many applications. Redux is a powerful tool, but it can also add complexity.
  • Verdict: 3 out of 5. Redux is a good choice for complex applications, but not always necessary.

3. The Cult of Condo Components

  • Belief: Components should be nested within other components to promote code organization.
  • Reality: Nesting components can make it difficult for React to optimize re-renders. Components should ideally be defined at the top level.
  • Verdict: 0 out of 5. Nested components are specifically discouraged in React documentation.

4. The Cult of Anti-Memoization

  • Belief: React’s useMemo and useCallback hooks are bad for performance and should be avoided.
  • Reality: These hooks can be helpful for performance optimization by preventing unnecessary re-computations.
  • Verdict: 0 out of 5. These hooks are valuable tools when used correctly.

5. The Cult that wants only Single Render

  • Belief: Components should only render once.
  • Reality: Components are designed to render whenever their data changes. Re-rendering is a core concept in React.
  • Verdict: 0 out of 5. Enforcing a single render goes against the core principles of React.

6. The Cult of Manual DOM Manipulation

  • Belief: It’s better to directly manipulate the DOM using methods like getElementById instead of relying on React's built-in mechanisms.
  • Reality: React is designed to manage the DOM efficiently. Directly manipulating the DOM can lead to inconsistencies and performance issues.
  • Verdict: 0 out of 5. Let React handle the DOM.

7. The Cult of Class Component Hierarchies

  • Belief: Class components should inherit from each other to create a hierarchy, similar to other frameworks.
  • Reality: React components are all subclasses of the base React.Component class. Inheriting from custom class hierarchies is discouraged.
  • Verdict: 0 out of 5. React uses composition rather than inheritance for component relationships.

The Importance of Adaptability

These cults stem from an unhealthy engineering mindset. Developers should avoid rigid beliefs and instead embrace adaptability and a willingness to learn new patterns. The key takeaway is to understand the core principles of React and avoid following outdated or misunderstood practices.

By shedding light on these common misconceptions, I encourage React developers to approach their work with a more critical and open mind. This will ultimately lead to writing cleaner, more efficient, and more maintainable React code.

I hope this blog post was helpful! If you have any questions or comments, feel free to leave them below.

I Tried Implementing Continuous Integration/Continuous Delivery (CI/CD): Did it boost my efficiency?
github-actions
ci-cd-pipeline
devops
repo-automation
pull-request

Generic CI/CD or DevOps pipeline setup

Introduction:

There is always room for automation if the task is repetitive, and I was looking for a way to delegate all the chores that I needed to do to a cloud server that does everything when I push my changes to the project repo.

I was skeptical of the hype surrounding CI/CD. All that automation and all those pipelines seemed like an unnecessary hurdle on the path to getting things done. But I was tired of the manual testing, the merge conflicts, and the last-minute scrambles before deployments. Efficiency was suffering, and something had to change. So, I took the plunge and implemented CI/CD in my workflow. Did it pay off? Buckle up, fellow developers, because I’m here to spill the tea.

The Initial Struggle:

Let’s be honest, setting up CI/CD isn’t a walk in the park. There’s a learning curve, a configuration to tackle, and the inevitable bumps along the road. Choosing the right tools, getting everyone on board, and ironing out the kinks took time and effort. But hey, no pain, no gain, right?

The Efficiency Revolution:

Once the dust settled, the magic started to happen. Here’s how CI/CD transformed my efficiency:

1. Automated Testing: No more tedious manual testing! Automated tests run with every commit, catching bugs early and often. This saved me countless hours and headaches down the line.

2. Faster Feedback: Every push triggers the pipeline, giving me instant feedback on the health of my code. This helped me identify and fix issues before they snowballed into major problems.

3. Streamlined Deployments: Gone are the days of manual deployments fraught with errors. CI/CD automates the deployment process, making it faster, safer, and less prone to human error.

4. Improved Collaboration: Version control and automated builds ensure everyone’s on the same page, fostering better collaboration and transparency within the team.

5. Peace of Mind: Knowing that my code is constantly tested and deployed with minimal effort gave me a newfound peace of mind. I could focus on writing good code instead of worrying about the deployment process.

Free CI/CD with GitHub and GitLab:

One of the biggest advantages of adopting CI/CD is its accessibility. Both GitHub and GitLab offer free plans that include basic CI/CD functionality. This is fantastic for individuals, small teams, or open-source projects starting their CI/CD journey.

With GitHub Actions, you can create basic automated workflows for building, testing, and deploying your code. Similarly, GitLab CI/CD allows you to define pipelines for running tests, building artifacts, and pushing them to desired environments. While their free plans have limitations compared to paid tiers, they provide a solid foundation to experience the benefits of CI/CD without significant upfront costs.

GitHub offers free CI/CD for public repositories through GitHub Actions. GitHub Actions can also be used for free on private repositories for up to 2,000 minutes of hosted workflows per month. If a developer hosts their own GitHub Action server, there is no limit to the number of minutes.

GitHub Actions is free if jobs execute on standard GitHub-hosted runners in public repositories or if you host your runners yourself.

GitLab offers free CI/CD for public, open-source projects on GitHub. The free tier of GitLab includes basic features, such as:

  • 5 GB of storage
  • 10 GB of data transfers per month
  • 400 CI/CD minutes per month
  • Five users per namespace

Vercel CI/CD integration into your favorite source code repositories.

Vercel has simplified the setup process to just one button click. I won't lie, it's been a breeze to just use the Vercel CI/CD pipeline. In my experience, it is one of the best ways to set up a CI/CD in a matter of minutes. and deploy your code with ease. The way Vercel builds your branch or a pull request and deploys it to a live URL is an incredible time saver since you can just open the URL and see the changes without having to manually run the project locally and test it out.

To try it out, just head to https://vercel.com/new and click that big deploy button to deploy your project.

Note: Now, when you are working on a project, you need to select a particular branching model since you can’t, and YOU SHOULD NOT, work in the main branch. The branching model that we are going to use is called Gitflow and is used widely in multiple projects. All code changes should be merged into the developbranch for this to play out nicely. When you are finally confident enough to do the final release of a major feature, you can merge the code into the mainbranch, and it will be deployed in a matter of minutes.

Here is an example of a GitHub action file that describes how to build the Python application, and it’s run every time the code push event occurs. It also includes steps for testing and creating the build artifact

name: Example Build Python App
on:
push:
#Event that triggers a build, a push to the main branch
branches:
- main
env:
environment: Prod
jobs:
#The list of jobs the workflow will execute
build:
runs-on: ubuntu-latest
#Runner that the job runs on, ubuntu in this case

steps:
#List of steps which will be executed by the job
- name: Checkout code
uses: actions/checkout@v2
#Action that checks out the code from the repository

- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: ${{ vars.python_version }}
#Variables can be populated from the github repo variables
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install ruff pytes
- name: Build
run: python setup.py build
- name: Test with pytest
run: pytest tests.py --doctest-modules --junitxml=junit/test-${{ env.environment }}-results.xml
#Env Vars can be populated from the job itself
- name: Upload pytest test results
uses: actions/upload-artifact@v3
#Artifact created from previous step is uploaded in this action
with:
name: pytest-results
path: junit/test-${{ env.environment }}-results.xml

An image showing the results of automated checks on the pull request:

Head over to https://docs.github.com/en/actions/quickstart for more concrete information.

Beyond the Free Plans:

As your project grows and your CI/CD needs evolve, you can explore paid plans on both platforms. They offer features like:

  • Increased build minutes: more time for complex workflows.
  • Parallel builds: faster execution times.
  • Advanced caching: improved efficiency and cost savings.
  • Integration with external services: streamlining your development process.

The choice between GitHub Actions and GitLab CI/CD comes down to your specific needs and preferences. Both offer compelling free plans and powerful paid options, making them excellent platforms to leverage for your CI/CD journey.

Not All Sunshine and Rainbows:

Of course, it’s not all sunshine and rainbows. CI/CD isn’t a magic bullet. Here are some of the challenges I encountered:

1. Time to set up: Setting up CI/CD requires time, effort, and sometimes financial investment. But trust me, it’s an investment that pays off in the long run.

2. Maintenance: Like any system, CI/CD pipelines need maintenance and upkeep. But the benefits far outweigh the effort involved.

3. Learning Curve: There’s a learning curve associated with CI/CD tools and concepts. However, plenty of resources are available to help you get started.

The Verdict:

So, am I more efficient now? A resounding YES! Implementing CI/CD has boosted my development speed, improved code quality, and reduced stress. It’s not a silver bullet, but it’s a powerful tool that can truly revolutionize your development workflow. If you’re on the fence, I urge you to give it a try. You won’t regret it!

Remember: This is just my experience. Share your own CI/CD journey in the comments below! Let’s discuss the challenges, the wins, and everything in between. Happy coding! 💪

Build Expo/React Native APK/AAB with Github Actions
android
github-actions
react-native
apk
expo

GitHub action building Android app APK/AAB artifact

Expo provides services to build your Android and iOS applications on their cloud, But the major drawback here is, that they have a maximum limit of 30 builds allowed per month.

To overcome this drawback, I thought of writing a GitHub action that will build the APK using the EAS build toolkit. This process took me a while to set up and I have documented the steps to be taken to create the build files and upload them as artifacts so we can download them.

Pre-requisite:

  • Github repo of your expo app
  • Expo account (Provides Token that is required by the EAS build tool)

After you have logged into your expo account, go ahead and create a robot token with admin access. This is required as the viewer or developer access tokens did not work and were giving permission errors during the build process.

Run eas init command and answer some basic questions, Once done , add the preview section as shown in the eas.json below

eas.json

{
"cli": {
"version": ">= 5.6.0"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"android": {
"buildType": "apk"
}
},
"production": {}
},
"submit": {
"production": {}
}
}

Here is the GitHub action file to build the app on GitHub servers and upload it as an artifact after completing the build.

android-build.yml

on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: 🏗 Setup repo
uses: actions/checkout@v3

- name: 🏗 Setup Node
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: yarn

- name: 🏗 Setup EAS
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}

- name: 📦 Install dependencies
run: yarn install

- name: 🚀 Build app
run: eas build --local --non-interactive --platform android --profile preview

- name: Upload Artifact GitHub Action
uses: actions/upload-artifact@v3
with:
name: assets-for-download
path: build-*.apk

The app.json configuration of my project

app.json

{
"expo": {
"owner": "myusername",
"name": "MY_APP",
"slug": "MY_APP",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"assetBundlePatterns": [
"**/*"
],
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
},
"package": "dev.myapp.studio"
},
"web": {
"favicon": "./assets/favicon.png"
},
"extra": {
"eas": {
"projectId": "5fafbba5-a3e3-4607-a6b5-5ad150a00132"
}
}
}
}

That’s all, now you can push your changes to the repo and the GitHub action will build the preview APK artifact.

Note: This APK file is to be treated as a preview only because we haven't signed the APK, those steps are skipped in this article. I’ll write about it once I have a final MVP of my app.

Unleashing the Power of React Native: Beyond the Basics
dx
abstraction
ota
react-native
cross-platform

React Native SDK

Introduction

React Native, a popular framework for building mobile applications often garners attention for its ability to leverage JavaScript and maintain a single codebase for both iOS and Android platforms. However, the true strength of React Native lies in its innovative design that opens the door to dynamic, over-the-air updates and a promising future with server components. In this article, we’ll explore the less-discussed aspects of React Native and why these features are game-changers for mobile app development.

The Magic of Abstraction

At its core, React Native offers a powerful abstraction that distinguishes it from traditional native app development. This abstraction separates the rendering engine (what is displayed on your device) from the logic that instructs it (JavaScript). This design allows you to change the user interface (UI) of your app by merely swapping out the JavaScript code without the need for a full application update.

In contrast, native development platforms like Swift UI for iOS or Kotlin for Android require pre-planned, native code for every potential UI scenario. With React Native, you don’t have to predefine every possible UI element. Instead, you can make dynamic changes on the fly, providing a much more flexible approach to mobile app development.

Over-the-Air Updates (OTA)

The ability to push over-the-air updates is a standout feature of React Native. Suppose you need to change the background color of a specific section of your app for a holiday or fix a minor UI bug. In traditional native development, you would have to submit an update to the App Store, wait for approval, and hope that users update their apps. This process can be time-consuming and uncertain, as not all users promptly update their apps.

In contrast, React Native allows you to modify the JavaScript code responsible for UI rendering, enabling quick fixes and adjustments. With OTA updates, you can deliver the new code to users without going through the App Store review process, ensuring a more responsive and dynamic user experience.

A Glimpse into Server Components

While React Native’s over-the-air updates are impressive, the future holds even more promise with server components. In the current React Native architecture, JavaScript fetches data from APIs and instructs the native layer on how to render it. However, server components introduce a revolutionary concept: replacing JSON data with structured markup that directly instructs the mobile device on how to render the UI.

With server components, the server’s payload contains instructions written in React, allowing the server to define not only what data should be rendered but also how it should be presented. This eliminates the need for complex client-side logic and custom rendering for different scenarios. Server components make it possible to offer entirely different app layouts based on specific user characteristics without having to distribute different JavaScript to individual users.

The Potential of Server Components on Mobile

Server components have the potential to reshape the mobile app development landscape. By focusing on delivering instructions instead of data, mobile apps can become more dynamic, responsive, and personalized. Developers can create user interfaces that adapt to specific user attributes, all controlled from the server side, without the need for complex client-side code management.

Conclusion

While React Native is often celebrated for its cross-platform capabilities and JavaScript integration, its true strengths lie in the power of abstraction, over-the-air updates, and the upcoming potential of server components. These features provide a new level of flexibility and responsiveness in mobile app development, allowing developers to create dynamic, user-centric applications that adapt to changing requirements with ease. As we look to the future of mobile app development, React Native and its innovative design are poised to play a leading role in shaping the next generation of mobile experiences.

LM Studio | Run open-source GPT models on your laptop
llm
gpt
lm-studio
api-server

Everything is running locally on your machine!

LM Studio makes it easy to run AI models locally on PC Mac and Linux If you are interested in trying the latest AI models and large language models trained in different ways.

The more powerful your laptop or desktop the better, but as long as you have at least 8GB of RAM you should be able to run at least one or two smaller AI models like Mistral and others. Using AI models locally opens up opportunities for private and small businesses to experiment and innovate with AI without expensive servers or cloud-based solutions.

LM studio

Have you ever wondered, how is it even possible to run such a large language model on your puny laptop? Well, it is made possible thanks to quantized models made available by the hugging face community.

A lot of popular model sizes vary in ranges from 2GB up to 30GB, Most popular ones like mistral-7B and llama-7B are around 5GB each.

With LM Studio, you can …

🤖 — Run LLMs on your laptop, entirely offline

👾 — Use models through the in-app Chat UI or spin up an OpenAI compatible API server

📂 — Download any compatible model files from HuggingFace

🤗 Repositories🔭 — Discover new & noteworthy LLMs in the app’s home page

Try LM Studio on your laptop now — https://lmstudio.ai/

How I Completed a Month-Long React Project in a Week
speed
production
reactjs
tools
frontend

React developer tools — Part 1

Recently I took up the development of a new project for a bank. The client wanted the application to be responsive on all platforms like mobile, desktop, and tablets. I received the Figma and validations for the input fields

  • There were about 10 screens in total
  • A login screen with subtle animations
  • A select currency screen with a feature to apply promo codes, multiple validations, edit modals, etc.
  • Enter details screen, which has 10 fields and validations for every field.
  • Preconfirmation screen and TNC modals.
  • Around 10+ API calls, avoided some API calls by having the dropdown values for city and state in the constants file.
  • Grid card authentication and OTP authentication screens
  • Finally a success screen

Well, all in all, the story had 24 Days of development effort required including designing UI screens, Functionality implementation, API integration, Unit Testing, etc

I will reveal the tools that I used to get the stuff done faster than you might already know

First of all, Let go of all your stigma about CSS. Hear me out it will save you tons of time.

I chose Tailwind to get started on development, as I had already used SASS and module.css , even styled-components in production-level projects. They were user-friendly and made code modular, but at the expense of more time needed to write more boilerplate code to achieve simple styling, sometimes simple flex and flex-col needed a new class to be created which is time-consuming when you are really just concerned with just making it look right

  1. Tailwind CSS was the perfect solution that I thought of giving a real shot, The project I was working on was already using Bootstrap, so I had to integrate Tailwind in such a way that doesn’t disturb or override the Bootstrap configuration.

A perfect way I found out was using the runtime JIT compiler provided over the cdn by tailwind, this was until I found one more good library called twind.style , this library primarily focuses on creating the most fastest and tiny JIT compiler for tailwind. and this one doesn’t need the build-step integration. Read more about it http://twind.style

I also highly recommend you to go through this writeup on the tailwind responsive design guide here — https://tailwindcss.com/docs/responsive-design

Keep a tailwind cheatsheet handy at all times.

2. React Hot Toast, This is a really cool lib that out of the box supports success and failure toasts along with custom toasts and has tailwind support too, really handy to show quick toasts for API success/failure notifications. Read more about it https://react-hot-toast.com/

3 . Zustand for global state management. Zustand is a breeze to work with and I couldn’t thank the developers of this library enough, it lets you quickly set up a globally accessible hook that provides you access to all the states and setters defined in your Zustand store. Go through the guide here — https://zustand-demo.pmnd.rs/

4. Figma to code plugin — by Builder.io, I have to say this is one of the insanely powerful AI tools I have come across that provides a much cleaner react code in tailwind or raw CSS. Unfortunately, I didn’t use this tool as it was unavailable at the time of development. https://www.builder.io/blog/figma-to-code-visual-copilot

5. Next UI— A component library that takes all your burden away, It has really well-crafted UI components that can be customized with tailwind also and has some really cool animations baked into them. When you are running short of time. I have tried Shadcn and RadixUI components as well, they are good at times. But I really don't like the nested component parts/structure that radix / shadcn brings in. Next UI was perfect for my case. Check it out —https://nextui.org/

6. Codeium vscode extension — to put it simply, it's GitHub copilot, but free! Never thought something this powerful was possible until the Chat GPT era. Really does what it claims, Immediately boosts 66% of your productivity.

Clap if you liked the post, and More power to you my friend! Code great things now! Off you go. 🐦

Red flags in a react codebase
red-flags
react
pitfalls
awareness

red flags in react codebase

🚩Functions named handleClick, handleSubmit

functions like

Seamless Linux environment in Windows, WSL for web developers
wsl
windows
seamless
fast
ubuntu

Seamless Linux environment in Windows, WSL for web developers

It’s definetely a treat to have best of both worlds at once place. Thanks to Microsoft , the developers dreams have come true now .

Seamlessly open linux apps and browse files of your ubuntu distro

And its pretty straight forward if you want to install the WSL (Windows subsystem for linux)

Install WSL on windows 10 or above using,

wsl --install

After installation you will be prompted to create a user, create the user and set your password

Configure default user

ubuntu config --default-user new_user_name

How to set default user for manually installed WSL distro?

I have installed vscode in my windows from the microsoft app store. Now when i want to start a web development project in my ubuntu , I open up the terminal and hit!

code .

Create a projects directory and check if you can see it in the file browser

I’ll be installing a tiny 28MB utility on ubuntu , just to check the windowing system,

Install mate-system-monitor

sudo apt install mate-system-monitor

Launch it by running mate-system-monitor

You will have a process/task manager show up.

Enjoy! Have fun with it.

Caution ! Before you Enter Trading
trading
caution
mindset

Caution ! Before you Enter Trading

There is so much of noise out there around this topic , you see everyone trading these days, I have some of my friends who also trade on regular basis. They are used to the losses they incur in the trading as they are convinced that one day all of a sudden they will be able to start making some real profits as they get more experience in trading.

Infact, a lot of influences on the social media we see are making most of their money by the courses they are selling , and showing them as very profitable investors. This is giving everyone a misconception that there is a good chunk of money to be made at ease once we learn how to trade. I don’t deny it , But its not easy as how they show it in tiktok/insta reels.

Understand this

Once you loose x% of your capital you need to win double the %x you lost just to recover the money you lost.

Take for example, you had capital of 10k and you take a trade and make a loss of 50% , now you need to make 100% profit on your next trade just to recover your initial capital

Read that again!

Tweak or Inject code into websites from your browser with Custom Tampermonkey extension.
javascript
inject
script
tampermonkey
browsers

Tamper the monkey ? What is it ?

Tampermonkey is a popular userscript manager that works with various web browsers, like Chrome, Safari, and Firefox. It allows users to inject custom JavaScript into any website, thereby customizing its behavior and look according to their preferences.

tampermonkey scripts dashboard/editor

1. For Development:

  • Rapid Prototyping: Instead of waiting for backend changes or deployments, frontend developers can make quick UI/UX changes using Tampermonkey.
  • Debugging: It offers a way to fix and test certain parts of web applications without going through the whole development process.

2. For Fun and Productivity:

  • Customization: Don’t like how a certain website looks? Change it! Want dark mode everywhere? Do it!
  • Automation: Automate repetitive tasks on websites. For instance, if you always fill out a form in a certain way, script it!

3. For Learning:

  • Understanding Web Apps: By interacting directly with web elements, budding developers can better understand how things work under the hood.

Getting Started with Tampermonkey

  1. Installation: Head to your browser’s extension store, search for Tampermonkey, and install it.
  2. Creating Your First Script: Once installed, click on the Tampermonkey icon and select “Create a new script”. A basic template appears. Here’s a basic example that changes the background of all paragraphs on a page to yellow:
// ==UserScript==
// @name Yellow Paragraphs
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Turn all paragraphs' backgrounds yellow.
// @author You
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
let paragraphs = document.querySelectorAll('p');
paragraphs.forEach(p => p.style.backgroundColor = 'yellow');
})();
  1. Use and Enjoy: Navigate to any website, and you’ll notice the changes in action.

You can also find scripts written by others by searching over here, for example youtube — https://www.userscript.zone/search?source=header&q=youtube

A Few Words of Caution

While Tampermonkey is a fantastic tool, remember to:

  • Always Backup: If you’ve written a particularly long or useful script, back it up. Scripts can get lost during browser updates.
  • Trust Sources: Only install scripts from trusted sources. Malicious scripts can compromise your data.
  • Performance Issues: Overloading with scripts can slow down your browser. Be selective about what you run.

Conclusion

Tampermonkey is more than just a tool for developers. It’s a bridge that empowers everyday users to craft their browsing experience. Whether you’re a full-stack wizard, a MERN enthusiast, or just someone who likes to tinker with web pages for fun, Tampermonkey offers endless possibilities to play, learn, and innovate.

© Rayan Fernandes. All Rights Reserved.