<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>NishanGiri Dev</title>
        <link>https://nishangiri.dev</link>
        <description>Read articles on Web Development, React, Nextjs, Javascript, Typescript, and many more. Stay ahead with latest updates!</description>
        <lastBuildDate>Fri, 13 Feb 2026 09:20:06 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>Next.js Feed Generator</generator>
        <language>en</language>
        <image>
            <title>NishanGiri Dev</title>
            <url>https://nishangiri.dev/logo.png</url>
            <link>https://nishangiri.dev</link>
        </image>
        <copyright>2024 NishanGiri Dev</copyright>
        <item>
            <title><![CDATA[Best 7 JavaScript Frameworks for 2024]]></title>
            <link>https://nishangiri.dev/blog/best-js-framework</link>
            <guid>https://nishangiri.dev/blog/best-js-framework</guid>
            <pubDate>Fri, 24 May 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Explore the top 7 JavaScript frameworks that will help you build modern, scalable, and high-performance web applications in 2024. Enhance your development skills with these powerful tools.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-05-24" />

<Image 
  src="/posts/Best 7 JavaScript Frameworks for 2024.png" 
  alt="Best 7 JavaScript Frameworks for 2024" 
  width={1200} 
  height={600} 
/>

JavaScript frameworks have revolutionized web development, making it easier to create robust and efficient web applications. In 2024, several frameworks stand out for their performance, community support, and advanced features. Here are the best 7 JavaScript frameworks to consider for your projects.

## 1. **React**

![React](../../public/posts/best-js-framework/react.png)

<CustomLink text="React" link="https://reactjs.org/" /> is a JavaScript library for building user interfaces, developed by Facebook. It has gained immense popularity due to its component-based architecture, virtual DOM, and strong community support.

### Key Features:
- Component-based architecture
- Virtual DOM for improved performance
- Strong ecosystem and community support

## 2. **Vue.js**

![Vue.js](../../public/posts/best-js-framework/vuejs.png)

<CustomLink text="Vue.js" link="https://vuejs.org/" /> is a progressive JavaScript framework for building user interfaces. It is designed to be incrementally adoptable, making it easy to integrate with other projects and libraries.

### Key Features:
- Reactive data binding
- Component-based architecture
- Comprehensive documentation and community support

## 3. **Angular**

![Angular](../../public/posts/best-js-framework/angular.png)

<CustomLink text="Angular" link="https://angular.io/" /> is a platform and framework for building single-page client applications using HTML and TypeScript. Developed by Google, Angular offers a robust set of tools and features for building large-scale applications.

### Key Features:
- Two-way data binding
- Dependency injection
- Comprehensive set of built-in tools and libraries

## 4. **Svelte**

![Svelte](../../public/posts/best-js-framework/svelte.png)

<CustomLink text="Svelte" link="https://svelte.dev/" /> is a radical new approach to building user interfaces. Instead of using a virtual DOM, Svelte compiles your components to highly efficient imperative code that directly manipulates the DOM.

### Key Features:
- No virtual DOM
- Highly efficient compiled output
- Simplicity and ease of use

## 5. **Next.js**

![Next.js](../../public/posts/best-js-framework/nextjs.png)

<CustomLink text="Next.js" link="https://nextjs.org/" /> is a React-based framework that provides infrastructure and simple development experience for server-side rendering (SSR) and static site generation (SSG). It's ideal for building high-performance web applications.

### Key Features:
- Server-side rendering and static site generation
- API routes
- Built-in CSS and Sass support

## 6. **Nuxt.js**

![Nuxt.js](../../public/posts/best-js-framework/nuxt.png)

<CustomLink text="Nuxt.js" link="https://nuxtjs.org/" /> is a framework for building Vue.js applications with server-side rendering, static site generation, and powerful configurations. It simplifies the development of complex applications.

### Key Features:
- Server-side rendering and static site generation
- Modular architecture
- Powerful configuration options

## 7. **Ember.js**

![Ember.js](../../public/posts/best-js-framework/ember.png)

<CustomLink text="Ember.js" link="https://emberjs.com/" /> is a framework for building ambitious web applications. It provides a strong convention-over-configuration philosophy and a robust set of tools to build scalable applications.

### Key Features:
- Convention over configuration
- Ember CLI for powerful tooling
- Strong community and documentation

---

## Conclusion

Choosing the right JavaScript framework can greatly enhance your productivity and the quality of your web applications. These 7 frameworks offer a range of features and capabilities that cater to different needs, from building simple user interfaces to complex, large-scale applications. Explore these options and see how they can help you create modern, scalable, and high-performance web applications in 2024!

---

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/Best 7 JavaScript Frameworks for 2024.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[7 Useful React Hooks You Should Know]]></title>
            <link>https://nishangiri.dev/blog/best-react-hooks</link>
            <guid>https://nishangiri.dev/blog/best-react-hooks</guid>
            <pubDate>Thu, 23 May 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Discover the top 7 React hooks that can simplify your development process and enhance your React applications in 2024. Learn how to use these hooks with practical examples.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-05-23" />

<Image 
  src="/posts/7 Useful React Hooks You Should Know.png" 
  alt="7 Useful React Hooks You Should Know" 
  width={1200} 
  height={600} 
/>

React hooks have transformed the way we write React components, making it easier to manage state, side effects, and other functionalities. Here are 7 useful React hooks that every developer should know.

## 1. useState

The `useState` hook is used to manage state in a functional component. It returns an array with two elements: the current state and a function to update it.

```jsx {4}{9} showLineNumbers
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;
```

## 2. useEffect

The `useEffect` hook lets you perform side effects in function components. It serves the same purpose as `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` in React classes.

```jsx /useEffect/
import React, { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prevSeconds => prevSeconds + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <p>Seconds elapsed: {seconds}</p>
    </div>
  );
}

export default Timer;
```

## 3. useContext

The `useContext` hook lets you subscribe to React context without introducing nested functions in your component.

```jsx {3}{6} showLineNumbers
import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);

  return (
    <button style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
      I am styled by theme context!
    </button>
  );
}

export default ThemedButton;
```

## 4. useReducer

The `useReducer` hook is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

```jsx {15} showLineNumbers
import React, { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>
        +
      </button>
      <button onClick={() => dispatch({ type: 'decrement' })}>
        -
      </button>
    </div>
  );
}

export default Counter;
```

## 5. useRef

The `useRef` hook returns a mutable ref object whose `.current` property is initialized to the passed argument. This object persists for the full lifetime of the component.

```jsx {4} showLineNumbers
import React, { useRef } from 'react';

function TextInputWithFocusButton() {
  const inputEl = useRef(null);

  const onButtonClick = () => {
    inputEl.current.focus();
  };

  return (
    <div>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </div>
  );
}

export default TextInputWithFocusButton;
```

## 6. useMemo

The `useMemo` hook returns a memoized value. Pass a "create" function and an array of dependencies. `useMemo` will only recompute the memoized value when one of the dependencies has changed.

```jsx /useMemo/
import React, { useMemo } from 'react';

function ExpensiveCalculationComponent({ num }) {
  const expensiveCalculation = useMemo(() => {
    return num ** 2;
  }, [num]);

  return <div>Expensive Calculation Result: {expensiveCalculation}</div>;
}

export default ExpensiveCalculationComponent;
```

## 7. useCallback

The `useCallback` hook returns a memoized callback. Pass an inline callback and an array of dependencies. `useCallback` will return a memoized version of the callback that only changes if one of the dependencies has changed.

```jsx /useCallback/
import React, { useState, useCallback } from 'react';

function IncrementButton() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount(count + 1);
  }, [count]);

  return <button onClick={increment}>Increment: {count}</button>;
}

export default IncrementButton;
```

---

### Conclusion

These 7 React hooks can greatly simplify your code and make your components more efficient and easier to understand. By mastering these hooks, you can take full advantage of React's powerful features and improve your development workflow. Try incorporating these hooks into your projects and see how they can enhance your React applications in 2024!

---

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/7 Useful React Hooks You Should Know.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Best 7 React UI Libraries for 2024]]></title>
            <link>https://nishangiri.dev/blog/best-react-ui-library</link>
            <guid>https://nishangiri.dev/blog/best-react-ui-library</guid>
            <pubDate>Tue, 04 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Discover the top React UI libraries for 2024. From Material-UI to Chakra UI, explore the best libraries to enhance your web development workflow with customizable, accessible, and performant components. Stay ahead with the latest in React UI tools.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-06-04" />

<Image 
  src="/posts/Best 7 React UI Libraries for 2024.png" 
  alt="Best 7 React UI Libraries for 2024" 
  width={1200} 
  height={600} 
/>

Hey there, fellow developers! 🌟 If you're diving into the world of web development, you know how crucial it is to have the right tools at your disposal. React, one of the most popular JavaScript libraries for building user interfaces, offers a ton of UI libraries to make your life easier. Whether you're crafting simple apps or complex, data-heavy interfaces, picking the right UI library can make a world of difference. In this post, we'll explore the best React UI libraries for 2024, showcasing their features, use cases, and what makes them stand out. Ready to level up your projects? Let’s get started!

## Table of Contents

<TableOfContents items={[
  { text: 'Why Use React Component Libraries?', href: '#why-use-react-component-libraries' },
  { text: 'Considerations When Choosing a Library', href: '#considerations-when-choosing-a-library' },
  { text: 'Material-UI (MUI)', href: '#1-material-ui-mui' },
  { text: 'Ant Design', href: '#2-ant-design' },
  { text: 'Chakra UI', href: '#3-chakra-ui' },
  { text: 'React Bootstrap', href: '#4-react-bootstrap' },
  { text: 'Tailwind UI', href: '#5-tailwind-ui' },
  { text: 'Semantic UI React', href: '#6-semantic-ui-react' },
  { text: 'Blueprint', href: '#7-blueprint' },
  { text: 'FAQs', href: '#faqs' }
]} />

## Why Use React Component Libraries?

Using React component libraries is like having a toolbox filled with ready-to-use tools. Here’s why they’re awesome:

- **Efficiency:** Pre-built components save you a ton of time. Instead of building everything from scratch, you can plug in components and focus on what makes your app unique.
- **Consistency:** Libraries ensure your app looks and feels cohesive. They follow design principles and UI patterns that keep everything uniform.
- **Customization:** Many libraries are highly customizable, letting you tweak components to match your project’s design perfectly.
- **Community Support:** Popular libraries often have large, active communities. This means plenty of resources, tutorials, and help when you need it.
- **Performance:** Optimized components can significantly boost your app's performance, especially when dealing with complex UIs.
- **Accessibility:** Many libraries prioritize accessibility, ensuring that your app is usable by everyone, regardless of their abilities.

## Considerations When Choosing a Library

Before you pick a library, consider these factors:

- **Customization:** How easy is it to tailor the components to fit your needs?
- **Community and Support:** Is there an active community and good documentation?
- **Performance:** Does the library affect your app’s performance, especially with large datasets?
- **Compatibility:** Will the library work with your current React version and other tools?
- **Accessibility:** Does the library support accessibility standards?
- **Update Frequency:** Is the library actively maintained and regularly updated?

## 1. Material-UI (MUI)

![Material-UI](../../public/posts/best-react-ui-library/mui.png)

<CustomLink text="Material-UI" link="https://mui.com/"/> is a powerhouse in the React world, known for its implementation of Google’s Material Design. It’s packed with components like buttons, forms, tables, and charts.

- **Features:**
  - **Pre-built Components:** Get started quickly with a wide range of ready-to-use components.
  - **Accessibility:** High standards ensure your app is usable by everyone.
  - **Customization:** Extensive theming support to make your app look exactly how you want.
  - **Community Support:** A large, active community with tons of resources and comprehensive documentation.

- **Use Cases:** Perfect for creating visually appealing and consistent applications, whether it’s a simple website or a complex enterprise solution.

- **Official Website:** <CustomLink text="Material-UI" link="https://mui.com/"/> 

## 2. Ant Design

![Ant Design](../../public/posts/best-react-ui-library/ant.png)

<CustomLink text="Ant Design" link="https://ant.design/"/>  stands out with its professional design and robust enterprise-level components. It’s heavily influenced by Chinese design principles, which gives it a unique edge.

- **Features:**
  - **Enterprise-level Components:** Includes everything from data tables to form layouts.
  - **Customization:** Easily customizable themes with CSS-in-JS.
  - **Internationalization:** Built-in support for multiple languages.
  - **Performance:** Highly optimized for fast and efficient applications.

- **Use Cases:** Ideal for enterprise applications that need to handle complex data management and require a polished, professional look.

- **Official Website:** <CustomLink text="Ant Design" link="https://ant.design/"/> 

## 3. Chakra UI

![Chakra UI](../../public/posts/best-react-ui-library/chakra.png)

<CustomLink text="Chakra UI" link="https://chakra-ui.com/"/>  is all about simplicity, modularity, and accessibility. It’s designed to be highly composable, making it easy to use and style.

- **Features:**
  - **Modular Architecture:** Import only the components you need to keep your app lightweight.
  - **Theming and Styling:** Easily match your design needs with comprehensive theming options.
  - **Accessibility:** Built-in features ensure your UI is usable by everyone.
  - **Community Support:** Strong support from a dedicated community.

- **Use Cases:** Great for developers who prioritize inclusivity and flexibility in their web applications.

- **Official Website:** <CustomLink text="Chakra UI" link="https://chakra-ui.com/"/> 

## 4. React Bootstrap

![React Bootstrap](../../public/posts/best-react-ui-library/bootstrap.png)

<CustomLink text="React Bootstrap" link="https://react-bootstrap.github.io/"/>  combines the simplicity of Bootstrap with the power of React. It provides a responsive grid system and a wide range of pre-built components.

- **Features:**
  - **Integration:** Seamlessly integrates with React and Bootstrap.
  - **Responsive Design:** Fully responsive components built with Flexbox.
  - **Customization:** Customizable components to suit your design needs.
  - **Documentation:** Extensive documentation and community resources for support.

- **Use Cases:** Perfect for projects that need a quick start with a reliable, responsive design framework.

- **Official Website:** <CustomLink text="React Bootstrap" link="https://react-bootstrap.github.io/"/> 

## 5. Tailwind UI

![Tailwind UI](../../public/posts/best-react-ui-library/tailwindui.png)

<CustomLink text="Tailwind UI" link="https://tailwindui.com/"/>, built on top of Tailwind CSS, offers beautifully designed, fully responsive UI components and templates that you can use in your React projects.

- **Features:**
  - **Customizable Components:** Fully customizable components and templates.
  - **Utility-First Approach:** Built with utility-first Tailwind CSS for rapid styling.
  - **Component Library:** Extensive component library with real-world examples.
  - **Accessibility:** Responsive and accessible by default.

- **Use Cases:** Ideal for developers who want to quickly build custom-styled user interfaces without writing extensive custom CSS.

- **Official Website:** <CustomLink text="Tailwind UI" link="https://tailwindui.com/"/> 

## 6. Semantic UI React

![Semantic UI React](../../public/posts/best-react-ui-library/semantic.png)

<CustomLink text="Semantic UI" link="https://react.semantic-ui.com/"/>  React brings the power of the Semantic UI framework to React, offering a declarative API and human-friendly HTML.

- **Features:**
  - **Declarative API:** Enables clean, readable code.
  - **Pre-built Components:** Wide range of pre-built components.
  - **Shorthand Props:** Allows for concise and efficient component customization.
  - **Integration:** Seamless integration with other React libraries.

- **Use Cases:** Perfect for developers who prefer a semantic approach to HTML and clean code structure.

- **Official Website:** <CustomLink text="Semantic UI" link="https://react.semantic-ui.com/"/> 

## 7. Blueprint

![Blueprint](../../public/posts/best-react-ui-library/blueprint.png)

<CustomLink text="Blueprint" link="https://blueprintjs.com/"/>  is designed for building complex, data-heavy applications, with a particular focus on desktop interfaces.

- **Features:**
  - **Data Visualization:** Extensive library of components for data visualization and manipulation.
  - **Desktop Focus:** Primarily designed for desktop applications but also responsive.
  - **Styling Options:** Comprehensive theming and styling options.
  - **TypeScript Support:** Excellent TypeScript support for type-safe coding.

- **Use Cases:** Best for applications requiring sophisticated data interaction and visualization, especially desktop-focused apps.

- **Official Website:** <CustomLink text="Blueprint" link="https://blueprintjs.com/"/> 

## FAQs

**1. What are the key factors to consider when choosing a React UI library?**  
When selecting a React UI library, think about customization options, community support, documentation quality, performance, and compatibility with other tools and frameworks you’re using.

**2. Which React UI library is best for enterprise-level applications?**  
Ant Design and Blueprint are great choices for enterprise-level applications due to their robust components, customization capabilities, and professional design aesthetics.

**3. How do I ensure the accessibility of my UI components?**  
Choose libraries like Material-UI, Chakra UI, and Semantic UI React, which prioritize accessibility and provide components that meet accessibility standards out-of-the-box.

**4. Can I use multiple React UI libraries in one project?**  
Yes, you can use multiple React UI libraries in a single project. Just make sure they don’t conflict with each other and that your app’s performance remains optimal.

**5. How frequently are these libraries updated?**  
Most popular React UI libraries are actively maintained and regularly updated. Checking their GitHub repositories for the latest commits and release notes can provide insights into their update frequency.

By addressing these common questions and offering detailed information on each library, this post aims to help developers make informed decisions and enhance their projects' user interfaces effectively.

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/Best 7 React UI Libraries for 2024.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Best 7 VS Code Extensions for Productivity in 2024]]></title>
            <link>https://nishangiri.dev/blog/best-vscode-extension</link>
            <guid>https://nishangiri.dev/blog/best-vscode-extension</guid>
            <pubDate>Sat, 18 May 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Discover the top 7 Visual Studio Code extensions that can enhance your productivity and streamline your development workflow in 2024.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-05-18" />

<Image 
  src="/posts/VS Code Extensions for Productivity in 2024.png" 
  alt="Best 7 VS Code Extensions for Productivity in 2024" 
  width={1200} 
  height={600} 
/>

Visual Studio Code (VS Code) is one of the most popular code editors among developers due to its flexibility, performance, and extensive customization options. One of the key features that make VS Code so powerful is its wide range of extensions. Here are the best 7 VS Code extensions for boosting your productivity in 2024.

## 1. **Prettier**

![Prettier](../../public/posts/best-vscode-extension/prettier.png)

<CustomLink text="Prettier" link="https://prettier.io/" /> is an opinionated code formatter that enforces a consistent style by parsing your code and re-printing it with its own rules. This extension saves you time on formatting and helps keep your codebase clean and readable.

### Key Features:
- Automatic code formatting
- Supports many languages
- Customizable configuration

## 2. **ESLint**

![ESLint](../../public/posts/best-vscode-extension/eslint.png)

<CustomLink text="ESLint" link="https://eslint.org/" /> is a static code analysis tool that identifies problematic patterns found in JavaScript code. It can be customized to enforce a wide range of coding styles and practices.

### Key Features:
- Identifies and fixes common problems
- Enforces coding standards
- Integrates with Prettier

## 3. **Live Share**

![Live Share](../../public/posts/best-vscode-extension/liveshare.png)

<CustomLink text="Live Share" link="https://visualstudio.microsoft.com/services/live-share/" /> by Microsoft enables real-time collaborative coding directly in VS Code. It's perfect for pair programming, code reviews, and troubleshooting issues with teammates.

### Key Features:
- Real-time collaboration
- Share debugging sessions
- Integrated chat and voice call support

## 4. **GitLens**

![GitLens](../../public/posts/best-vscode-extension/gitlens.png)

<CustomLink text="GitLens" link="https://gitlens.amod.io/" /> supercharges the Git capabilities of VS Code. It helps you visualize code authorship through Git blame annotations and code lens, making it easier to understand the history and evolution of your codebase.

### Key Features:
- Git blame annotations
- Code lens with author and commit info
- Enhanced code review and exploration

## 5. **Live Server**

![Live Server](../../public/posts/best-vscode-extension/liveserver.png)

<CustomLink text="Live Server" link="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer" /> is an extension that launches a local development server with live reload feature for static and dynamic pages. It’s a must-have for web developers who want to see their changes in real-time.

### Key Features:
- Real-time browser reload on file save
- Supports static and dynamic pages
- Customizable settings

## 6. **Path Intellisense**

![Path Intellisense](../../public/posts/best-vscode-extension/pathintellisense.png)

<CustomLink text="Path Intellisense" link="https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense" /> provides autocompletion for file paths, which speeds up the process of importing files and assets into your projects.

### Key Features:
- Autocomplete for file paths
- Supports multiple languages
- Easy navigation to files

## 7. **VS Code Icons**

![VS Code Icons](../../public/posts/best-vscode-extension/vscodeicons.png)

<CustomLink text="VS Code Icons" link="https://marketplace.visualstudio.com/items?itemName=vscode-icons-team.vscode-icons" /> enhances the file icons in Visual Studio Code with a set of high-quality, custom icons for different file types, making it easier to navigate and understand your project structure.

### Key Features:
- Custom file icons for different file types
- Improved project visualization
- Easy recognition of file types

---

## Conclusion

Enhancing your VS Code setup with these extensions can significantly improve your productivity and streamline your development workflow. Whether you're writing code, collaborating with teammates, or debugging applications, these extensions offer powerful features that can help you work smarter and more efficiently. Try them out and see how they can transform your coding experience in 2024!

---

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/VS Code Extensions for Productivity in 2024.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Creating Reusable Components in React: A Comprehensive Guide with Examples]]></title>
            <link>https://nishangiri.dev/blog/creating-resuable-component-react</link>
            <guid>https://nishangiri.dev/blog/creating-resuable-component-react</guid>
            <pubDate>Tue, 02 Jul 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn how to create reusable components in React with this comprehensive guide. Explore best practices, step-by-step examples, and tips for efficient and maintainable code. Perfect for developers aiming to streamline their React projects.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-07-02" />

<Image
  src="/posts/Creating Reusable Components in React.png"
  alt="Creating Reusable Components in React: A Comprehensive Guide with Examples"
  width={1200}
  height={600}
/>

Hi there! 👋 In this guide, we’re going to explore how to build reusable components in React. By the end of this journey, you'll be a pro at creating components that you can use across multiple projects, making your development process faster and more efficient. Let’s dive in!

### Table of Contents

<TableOfContents
  items={[
    { text: "What is a React Reusable Component?", href: "#what-is-a-react-reusable-component"},
    { text: "Why Reusable Components?", href: "#why-reusable-components" },
    {
      text: "Principles of Reusable Components",
      href: "#principles-of-reusable-components",
    },
    {
      text: "Step-by-Step Guide to Building Reusable Components",
      href: "#step-by-step-guide-to-building-reusable-components",
      subItems: [
        { text: "Component Design", href: "#component-design" },
        { text: "Prop Management", href: "#prop-management" },
        { text: "Styling", href: "#styling" },
        { text: "State Management", href: "#state-management" },
        {
          text: "Testing and Documentation",
          href: "#testing-and-documentation",
        },
      ],
    },
    { text: "Best Practices", href: "#best-practices" },
    { text: "Conclusion", href: "#conclusion" },
  ]}
/>
---

## What is a React Reusable Component?

A React reusable component is a self-contained module that can be used in different parts of your application without rewriting code. Think of it as a versatile building block that can be configured to serve multiple purposes, enhancing both development speed and code consistency.

## Why Reusable Components?

Think of reusable components as the LEGO blocks of your React applications. They offer so many benefits:

**Consistency**: Your app will have a uniform look and feel.

**Efficiency**: Save time by not writing the same code over and over.

**Scalability**: Easily grow your app by using components as building blocks.

**Maintainability**: Simplify updates and bug fixes with centralized code.

For more on the benefits of reusable components, check out this <CustomLink text="comprehensive guide on component-based architecture" link="https://handsonreact.com/docs/component-architecture" />

## Principles of Reusable Components

When building reusable components, keep these key principles in mind:

**Single Responsibility**: Each component should do one thing and do it well.

**Composability**: Components should be easy to combine with others.

**Configurability**: Use props to customize behavior without changing the component's code.

**Isolation**: Avoid side effects that can affect other parts of the app.

## Step-by-Step Guide to Building Reusable Components

### Component Design

Let’s start simple. Here’s how you can design a basic button component.

```jsx
import React from "react";

const Button = ({ label, onClick, style, type = "button" }) => {
  return (
    <button type={type} onClick={onClick} style={style}>
      {label}
    </button>
  );
};

export default Button;
```

### Prop Management

Props are your best friends when it comes to reusable components. They allow you to customize your components effortlessly.

```jsx
const Button = ({
  label,
  onClick,
  style,
  type = "button",
  disabled = false,
}) => {
  return (
    <button type={type} onClick={onClick} style={style} disabled={disabled}>
      {label}
    </button>
  );
};
```

For a deeper understanding of props, check out the official <CustomLink text="React documentation on props" link="https://react.dev/learn/passing-props-to-a-component"/>

### Styling

Styling can be handled in many ways. Here’s an example using styled-components.

```jsx
import styled from "styled-components";

const StyledButton = styled.button`
  background-color: #6200ee;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;

  &:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }
`;

const Button = ({ label, onClick, disabled = false }) => {
  return (
    <StyledButton onClick={onClick} disabled={disabled}>
      {label}
    </StyledButton>
  );
};
```

Learn more about <CustomLink text="styled-components " link="https://styled-components.com/"/> to enhance your styling techniques.

### State Management

For components that need internal state, use hooks. Here’s a simple toggle button example.

```jsx
import React, { useState } from "react";

const ToggleButton = ({ initialState = false }) => {
  const [toggled, setToggled] = useState(initialState);

  return (
    <button onClick={() => setToggled(!toggled)}>
      {toggled ? "On" : "Off"}
    </button>
  );
};
```

For more details on managing state with hooks, check out the official <CustomLink text="React documentation on hooks" link="https://react.dev/reference/react/hooks"/>

### Testing and Documentation

Good components are well-tested and documented. Use tools like Jest for testing and Storybook for documentation.

```jsx
import { render, screen, fireEvent } from "@testing-library/react";
import Button from "./Button";

test("renders button with label", () => {
  render(<Button label="Click me" />);
  expect(screen.getByText("Click me")).toBeInTheDocument();
});

test("calls onClick handler", () => {
  const handleClick = jest.fn();
  render(<Button label="Click me" onClick={handleClick} />);
  fireEvent.click(screen.getByText("Click me"));
  expect(handleClick).toHaveBeenCalledTimes(1);
});
```

Explore more about <CustomLink text="Jest" link="https://jestjs.io/docs/tutorial-react" /> and <CustomLink text="Storybook" link="https://storybook.js.org/addons/@storybook/testing-react" /> to enhance your testing and documentation processes.

### Best Practices

- **Prop Types**: Use prop-types or TypeScript for type checking.
- **Default Props**: Define default values for props to ensure robustness.
- **Composition**: Design components to be easily composable.
- **Documentation**: Document usage examples and props clearly.

## Conclusion

Building reusable components in React is a game-changer for productivity and code quality. By following the steps and best practices in this guide, you’ll be able to create components that are easy to use and adapt across different projects.

For more insights on React development, check out <CustomLink text="React’s official blog" link="https://react.dev/"/>

Happy coding! 🎉
]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/Creating Reusable Components in React.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[The Ultimate Docker Cheat Sheet for Developers]]></title>
            <link>https://nishangiri.dev/blog/docker-cheat-sheets</link>
            <guid>https://nishangiri.dev/blog/docker-cheat-sheets</guid>
            <pubDate>Mon, 10 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Discover the ultimate Docker cheat sheet for developers. Learn essential Docker commands, best practices, and tips for optimizing Docker usage. This comprehensive guide covers everything from basic commands to advanced techniques, Docker Compose, and security best practices to streamline your development workflow.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-06-10" />

<Image
  src="/posts/The Ultimate Docker Cheat Sheet.png"
  alt="The Ultimate Docker Cheat Sheet for Developers"
  width={1200}
  height={600}
/>

### Table of Contents
<TableOfContents items={[
  { text: 'Introduction?', href: '#introduction' },
  { text: 'What is Docker?', href: '#what-is-docker' },
  { text: 'Basic Docker Commands', href: '#basic-docker-commands' },
  { text: 'Working with Docker Images', href: '#working-with-docker-images' },
  { text: 'Managing Docker Containers', href: '#managing-docker-containers' },
  { text: 'Docker Networks and Volumes', href: '#docker-networks-and-volumes' },
  { text: 'Docker Compose Basics', href: '#docker-compose-basics' },
  { text: 'Advanced Docker Commands', href: '#advanced-docker-commands' },
  { text: 'Tips and Tricks for Efficient Docker Usage', href: '#tips-and-tricks-for-efficient-docker-usage' },
  { text: 'Conclusion', href: '#conclusion' },
  { text: 'FAQs', href: '#faqs' }
]} />

## Introduction
In the ever-evolving world of web development, Docker has become an indispensable tool for developers. Whether you're working on a small project or a large-scale application, Docker simplifies the process of creating, deploying, and managing applications using containerization. This cheat sheet provides a comprehensive guide to essential Docker commands and tips, making it easier for you to work efficiently with Docker.

## What is Docker?
<CustomLink text="Docker" link="https://www.docker.com/" /> is an open-source platform designed to automate the deployment, scaling, and management of applications. It allows developers to package applications and their dependencies into containers—lightweight, portable units that can run consistently across different environments.

**Advantages of Docker:**
- Consistency across development, testing, and production environments.
- Faster and more efficient deployment of applications.
- Improved resource utilization.
- Simplified dependency management.

Common use cases for Docker in web development include creating isolated development environments, running microservices, and simplifying CI/CD pipelines.

## Basic Docker Commands

---

**Check Docker Version:**
```sh
docker --version
```
Displays the installed Docker version.

---

**Pull an Image from Docker Hub:**
```sh
docker pull [image]
```
Fetches an image from Docker Hub.

---

**Run a Container:**
```sh
docker run [image]
```
Creates and starts a container from the specified image.

---

**List Running Containers:**
```sh
docker ps
```
Displays a list of all running containers.

---

**Stop a Running Container:**
```sh
docker stop [container]
```
Stops the specified container.

---

**Remove a Container:**
```sh
docker rm [container]
```
Deletes the specified container.

---

## Working with Docker Images

**Build an Image:**
```sh
docker build -t [name] .
```
Builds an image from a Dockerfile in the current directory.

---

**List Local Images:**
```sh
docker images
```
Displays all images stored locally.

---

**Remove an Image:**
```sh
docker rmi [image]
```
Deletes the specified image.

---

## Example Dockerfile:
```docker
# Use an official Node.js runtime as a parent image
FROM node:14

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in package.json
RUN npm install

# Make port 8080 available to the world outside this container
EXPOSE 8080

# Run app.js when the container launches
CMD ["node", "app.js"]
```

---

## Managing Docker Containers

**Start a Stopped Container:**
```sh
docker start [container]
```
Starts a container that was previously stopped.

---

**Execute a Command in a Running Container:**
```sh
docker exec -it [container] /bin/bash
```
Opens a bash shell inside the running container.

---

**View Container Logs:**
```sh
docker logs [container]
```
Displays the logs of the specified container.

---

**Inspect Container Details:**
```sh
docker inspect [container]
```
Shows detailed information about the specified container.

---

## Docker Networks and Volumes

**List Networks:**
```sh
docker network ls
```
Displays all Docker networks.

---

**Create a Network:**
```sh
docker network create [network_name]
```
Creates a new Docker network.

---

**List Volumes:**
```sh
docker volume ls
```
Displays all Docker volumes.

---

**Create a Volume:**
```sh
docker volume create [volume_name]
```
Creates a new Docker volume.

---

**Example of Using Volumes:**
```sh
docker run -d -v myvolume:/app/data myimage
```
Mounts the myvolume volume to the /app/data directory in the container.

---

## Docker Compose Basics

**Introduction to Docker Compose:**

Docker Compose is a tool for defining and running multi-container Docker applications. With a simple docker-compose.yml file, you can configure your application’s services, networks, and volumes.

---

## Example docker-compose.yml File:
```yml
version: '3'
services:
  web:
    image: nginx
    ports:
      - "80:80"
  app:
    image: node:14
    volumes:
      - .:/app
    command: npm start
    depends_on:
      - web
```

---

## Common Docker Compose Commands:
**Start Services:**
```sh
docker-compose up
```
Starts all services defined in the docker-compose.yml file.

---

**Stop Services:**
```sh
docker-compose down
```
Stops all running services and removes containers, networks, volumes, and images created by up.

---

**View Logs:**
```sh
docker-compose logs
```
Displays logs from all services.

---

## Advanced Docker Commands

**Pause and Unpause a Container:**
```sh
docker pause [container]
docker unpause [container]
```
Pauses and unpauses a running container respectively.

---

**Commit Changes to a New Image:**
```sh
docker commit -m "commit message" -a "author" [container] [username/image_name:tag]
```
Saves the changes in a container to a new image.

---

**Cleanup Unused Resources:**
```sh
docker system prune
```
Removes all stopped containers, unused networks, dangling images, and build cache.

---

## Tips and Tricks for Efficient Docker Usage

### Optimize Dockerfile for Smaller Image Sizes:
- Use multi-stage builds to keep images lean.
- Minimize the number of layers by combining commands.
- Clean up unnecessary files and caches in your Dockerfile.

**Using .dockerignore File:***

Similar to .gitignore, a .dockerignore file can be used to exclude files and directories from being copied into the Docker image, reducing build context size and speeding up the build process.

## Example .dockerignore File:
```sh
node_modules
.git
Dockerfile
README.md
```

### Docker Hub vs. Private Registries:

**Docker Hub:** Publicly accessible, easy to use, and integrates with Docker CLI. However, it's not ideal for private images.

**Private Registries:** Provide better security and control over your images. Consider using solutions like Docker Trusted Registry or third-party services like AWS ECR or Azure Container Registry.

### Security Best Practices:

- Regularly scan images for vulnerabilities.
- Use official images as base images.
- Avoid running containers as the root user.
- Keep Docker up to date.

## Conclusion
Docker has revolutionized the way we develop, ship, and run applications. By mastering the essential Docker commands and best practices outlined in this cheat sheet, you can streamline your development workflow and boost productivity. Bookmark this page and refer to it whenever you need a quick Docker reference. Don't forget to share your own Docker tips and tricks in the comments below!

### Frequently Asked Questions (FAQs)

**1. What is Docker and why is it used?**

Docker is a platform designed to simplify the creation, deployment, and running of applications using containers. Containers allow developers to package an application with all its dependencies and run it in any environment, ensuring consistency across different stages of development and deployment.

**2. How do I install Docker on my system?**

To install Docker, visit the [Docker website](https://www.docker.com/products/docker-desktop) and download Docker Desktop for your operating system (Windows, Mac, or Linux). Follow the installation instructions provided for your specific OS.

**3. What are the basic Docker commands every developer should know?**

Some of the basic Docker commands include:
- `docker --version`: Check the installed Docker version.
- `docker pull [image]`: Pull an image from Docker Hub.
- `docker run [image]`: Run a container from the specified image.
- `docker ps`: List running containers.
- `docker stop [container]`: Stop a running container.
- `docker rm [container]`: Remove a container.

**4. How do I create a Dockerfile?**

A Dockerfile is a text file that contains instructions on how to build a Docker image. Here’s a simple example:
```docker
# Use an official Node.js runtime as a parent image
FROM node:14

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in package.json
RUN npm install

# Make port 8080 available to the world outside this container
EXPOSE 8080

# Run app.js when the container launches
CMD ["node", "app.js"]
```

To build an image from this Dockerfile, use the command:
```sh
docker build -t my-node-app .
```

**5. How do I clean up unused Docker resources?**

To free up space and keep your system clean, you can use the following commands:

- `docker system prune`: Remove all stopped containers, unused networks, dangling images, and build cache.
- `docker image prune -a`: Remove all unused images.
- `docker container prune`: Remove all stopped containers.
- `docker volume prune`: Remove all unused volumes.

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/The Ultimate Docker Cheat Sheet.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[How to Dockerize NextJS and Publish it to a Git Registry]]></title>
            <link>https://nishangiri.dev/blog/docker-nextjs-github</link>
            <guid>https://nishangiri.dev/blog/docker-nextjs-github</guid>
            <pubDate>Fri, 07 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn how to Dockerize your NextJS application and publish it to a Git registry. This comprehensive guide covers everything from creating a Dockerfile to automating the deployment process with CI/CD pipelines, ensuring efficient workflow and consistent application behavior across various environments.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-06-07" />

<Image
  src="/posts/How to Dockerize NextJS and Publish it to a Git Registry.png"
  alt="How to Dockerize NextJS and Publish it to a Git Registry"
  width={1200}
  height={600}
/>

In today's fast-paced development environment, containerization has become a critical skill for web developers. Docker allows us to package applications with all their dependencies, ensuring consistent behavior across different environments. When combined with NextJS, a powerful React framework, and Git, a robust version control system, you can streamline your development workflow and enhance collaboration.

In this comprehensive guide, we will walk you through the process of Dockerizing a NextJS application and publishing it to a Git registry. By the end of this tutorial, you'll have a solid understanding of Docker basics, how to containerize your NextJS app, and the steps to automate the process using CI/CD pipelines. Let's get started!

## Table of Contents
<TableOfContents items={[
  { text: 'Introduction', href: '#introduction' },
  { text: 'Prerequisites', href: '#prerequisites' },
  { text: 'Setting Up the NextJS Project', href: '#setting-up-the-nextjs-project' },
  { text: 'Writing the Dockerfile', href: '#writing-the-dockerfile' },
  { text: 'Building the Docker Image', href: '#building-the-docker-image' },
  { text: 'Running the Docker Container', href: '#running-the-docker-container' },
  { text: 'Pushing the Docker Image to a Git Registry', href: '#pushing-the-docker-image-to-a-git-registry' },
  { text: 'Automating the Process with CI/CD', href: '#automating-the-process-with-cicd' },
  { text: 'Conclusion', href: '#conclusion' },
  { text: 'FAQs', href: '#faqs' }
]} />

## Introduction
Containerization has revolutionized the way we develop, deploy, and manage applications. <CustomLink text="Docker" link="https://www.docker.com/" />, a popular containerization platform, enables developers to package applications along with their dependencies into a standardized unit called a Docker image. This image can then be run in any environment that supports Docker, ensuring consistent behavior across development, testing, and production environments.

<CustomLink text="NextJs" link="https://nextjs.org/" />, a React framework for production, enables developers to build server-side rendering and static web applications easily. By containerizing a NextJS application, we can ensure that it runs smoothly in different environments without any dependency issues.

In this tutorial, we will learn how to Dockerize a NextJS application and publish it to a Git registry. This process involves several steps, including writing a Dockerfile, building the Docker image, running the Docker container, and automating the process using Continuous Integration/Continuous Deployment (CI/CD) pipelines.

## Prerequisites
Before we start, make sure you have the following software installed on your system:
- **Docker:** <CustomLink text="Install Docker" link="https://docs.docker.com/get-docker/" />
- **Node.js:** <CustomLink text="Install Node.js" link="https://nodejs.org/" />
- **Git:** <CustomLink text="Install Git" link="https://git-scm.com/" />

Additionally, you should have a basic understanding of the following concepts:
- Basic knowledge of NextJS and JavaScript.
- Familiarity with the command line interface.
- Understanding of Git and version control.

## Setting Up the NextJS Project
First, let's set up a basic NextJS project. If you don't have an existing NextJS project, you can create one using the following command:

```bash
npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
```

This will create a new NextJS application in the my-nextjs-app directory. You can start the development server to ensure everything is set up correctly:
```bash
npm run dev
```
Open your browser and navigate to http://localhost:3000. You should see the default NextJS welcome page.

## Writing the Dockerfile
A Dockerfile is a text document that contains instructions for Docker to build an image. Let's create a Dockerfile in the root directory of your NextJS project. Here’s an example Dockerfile for a NextJS application:
```dockerfile
# Stage 1: Install dependencies only when needed
FROM node:16-alpine AS deps
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile

# Stage 2: Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY . .
RUN yarn build

# Stage 3: Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
EXPOSE 3000
CMD ["node", "server.js"]
```

## Explanation:
- **Stage 1:** Install dependencies only when needed.
- **Stage 2:** Rebuild the source code only when needed.
- **Stage 3:** Create a production image, copy all the necessary files, and expose port 3000.

Using multi-stage builds helps keep the Docker image size small and optimized by separating the build and runtime environments.

## Building the Docker Image
To build the Docker image, run the following command in the root directory of your project:
```bash
docker build -t my-nextjs-app .
```

This command will create a Docker image with the tag my-nextjs-app. You can verify the creation of the Docker image by running:
```bash
docker images
```

## Running the Docker Container
Now that we have our Docker image, let's run it in a Docker container. Use the following command to run the Docker container:
```bash
docker run -p 3000:3000 my-nextjs-app
```
This will start the Docker container and map port 3000 of the container to port 3000 on your host machine. Open your browser and navigate to http://localhost:3000 to see your NextJS application running inside the Docker container.

## Pushing the Docker Image to a Git Registry
To push your Docker image to a Git registry, you need to tag your image with the registry's URL. Here's an example using GitHub Container Registry:

1. **Login to GitHub Container Registry:**
   ```bash
   echo $GITHUB_TOKEN | docker login ghcr.io -u USERNAME --password-stdin
   ```
2. **Tag the Docker image:**
    ```bash
    docker tag my-nextjs-app ghcr.io/USERNAME/my-nextjs-app:latest
    ```
3. **Push the Docker image:**
    ```bash
    docker push ghcr.io/USERNAME/my-nextjs-app:latest
    ```

Replace USERNAME with your GitHub username. This will push your Docker image to the GitHub Container Registry.

## Automating the Process with CI/CD
To automate the process of building and pushing Docker images, we can use GitHub Actions. Create a .github/workflows/publish.yml file in your repository and add the following content:
```yml
name: Build and Push Docker Image

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Build the Docker image
        run: docker build . --tag ghcr.io/USERNAME/my-nextjs-app:latest
      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v1
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Push the Docker image
        run: docker push ghcr.io/USERNAME/my-nextjs-app:latest
```

This GitHub Actions workflow will automatically build and push your Docker image to the GitHub Container Registry whenever you push changes to the main branch.

## Conclusion
In this tutorial, we covered the steps to Dockerize a NextJS application and publish it to a Git registry. By containerizing your NextJS application, you ensure consistent behavior across different environments, making your development workflow more efficient and reliable. Additionally, automating the process with CI/CD pipelines can significantly enhance your productivity.

We hope you found this guide helpful. Feel free to share your experiences or ask questions in the comments section below.

## FAQs

1. **What is Docker and why should I use it?**
   Docker is a platform that enables developers to package applications and their dependencies into a standardized unit called a Docker image. This image can run consistently across different environments, reducing the "it works on my machine" problem.

2. **Why use NextJS for my web applications?**
   NextJS is a powerful React framework that enables server-side rendering and static site generation. It simplifies the development process and enhances the performance of web applications.

3. **How do I handle environment variables in Docker?**
   You can use the `ARG` and `ENV` instructions in the Dockerfile to pass environment variables. For example:

   ```dockerfile
   ARG NEXT_PUBLIC_API_URL
   ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}
   ```
You can then pass these variables during the build process using the `--build-arg` flag.

4. **What is GitHub Actions?**
   GitHub Actions is a CI/CD platform that allows you to automate your build, test, and deployment pipelines. You can create workflows that trigger on specific events, such as pushing changes to a branch.

5. **Can I use other Git registries besides GitHub Container Registry?**
   Yes, you can use other Git registries such as GitLab Container Registry, Docker Hub, and others. The process is similar, but the commands and configuration may vary slightly.

By following these steps, you can improve your development workflow and ensure consistent application behavior across different environments. Automating the process with CI/CD pipelines can significantly enhance your productivity.

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/How to Dockerize NextJS and Publish it to a Git Registry.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Mastering Flexbox in CSS: A Comprehensive Guide for Responsive Web Design]]></title>
            <link>https://nishangiri.dev/blog/flexbox-in-css</link>
            <guid>https://nishangiri.dev/blog/flexbox-in-css</guid>
            <pubDate>Fri, 30 Aug 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn how to master Flexbox in CSS with our comprehensive guide. Understand the key properties like flex-grow, flex-shrink, and flex-basis to create responsive, flexible web layouts. Perfect for web developers looking to enhance their design skills and improve website performance.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-08-30" />

<Image
  src="https://drive.google.com/uc?export=view&id=1IvuO7Z32xuwQfn8sHsJUVuY85TYia15T"
  alt="Mastering Flexbox in CSS: A Comprehensive Guide for Responsive Web Design"
  width={1200}
  height={600}
/>
Flexbox is a powerful tool in CSS that helps you create layouts that adjust smoothly
to different screen sizes. Whether you're building a simple navigation bar or a complex
grid, Flexbox makes it easier to design responsive and flexible web pages. In this
guide, we’ll explore the basics of Flexbox, break down its key properties, and show
you how to use it to make your web designs more adaptive and user-friendly.

## Getting Started with Flexbox

To help you get hands-on with Flexbox, let's start with a simple example. We'll use basic HTML and CSS to create a layout with multiple boxes inside a container. This will allow you to see Flexbox in action and understand how it can be used to arrange elements on your web page.

**HTML Structure**

Here’s the basic HTML structure for our example

```HTML
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mastering Flexbox in CSS</title>
    <link rel="stylesheet" href="./style.css">
  </head>
  <body>
    <div class="main">
      <div class="box">1</div>
      <div class="box b2">2</div>
      <div class="box">3</div>
      <div class="box">4</div>
      <div class="box">5</div>
    </div>
  </body>
</html>
```

This structure includes a container `<div>` with a class of main, and five child `<div>` elements inside it, each with a class of box. These boxes are where we'll apply Flexbox styling.

**Basic CSS Styling**

Let's start with some basic CSS to style the boxes and the container:

```css
* {
  margin: 0;
}

.main {
  background-color: #1b212c;
}

.box {
  background-color: #447bbe;
  color: #f8f8ff;
  font-size: 30px;
  padding: 35px;
  margin: 10px;
  width: 20px;
}
```

**Result:**

<Image
  src="https://drive.google.com/uc?export=view&id=1QaERZxiSv3OMgqI-9GYYRet8o_pV-OL-"
  alt="Flex box: step-1"
  width={1200}
  height={600}
/>

## display: flex

To turn this basic layout into a Flexbox-powered layout, we’ll need to update the .main class with `flex-box` properties:

```css
.main {
  background-color: #1b212c;
  display: flex;
}
```

**Result:**

<Image
  src="https://drive.google.com/uc?export=view&id=1KCNw7oU0tzZ9afD7PSkPYYvlzNbGXOeB"
  alt="Flex box: step-2.0"
  width={1200}
  height={600}
/>

## flex-direction: row

You might have noticied that just by applying `display: flex`. The layout has changed to row layout. This is because of its default behaviour which is same as adding `flex-direction: row` property.
Lets add `flex-direction` property and see how the layout changes.

```css
.main {
  background-color: #1b212c;
  display: flex;
  flex-direction: row;
}
```

**Result:**

<Image
  src="https://drive.google.com/uc?export=view&id=1KCNw7oU0tzZ9afD7PSkPYYvlzNbGXOeB"
  alt="Flex box: step-2.1"
  width={1200}
  height={600}
/>

After adding the `flex-direction: row` property changes nothing as we are setting it to row which is the default behaviour.

## justify-content

Now let's check what `justify-content` propery actually does.

```css
.main {
  background-color: #1b212c;
  display: flex;
  flex-direction: row;
  justify-content: center;
}
```

**Result**

<Image
  src="https://drive.google.com/uc?export=view&id=16mnspINeK2R-_dgY3mEokDtMBdHLEJFy"
  alt="Flex box: step-3"
  width={1200}
  height={600}
/>
The `justify-content: center` centers the flex items horizontally within the .main
container. It has several values, each controlling the horizontal alignment of flex
items within the container:

**flex-start:** Aligns items to the start (left) of the container.

**flex-end:** Aligns items to the end (right) of the container.

**center:** Centers items horizontally in the container.

**space-between:** Distributes items evenly with the first item at the start and the last item at the end.

**space-around:** Distributes items evenly with equal space around each item.

**space-evenly:** Distributes items so that the space between them is equal, including at the edges of the container.

These options give you flexibility in how you arrange items horizontally within a Flexbox container. Play around these values to see how the layout in the container changes.

## flex-direction: column

Now, lets change `flex-direction` property and see how the layout changes.

```css
.main {
  background-color: #1b212c;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
```

**Result:**

<Image
  src="https://drive.google.com/uc?export=view&id=1EWO7UQ4wCFegsFS5xHooMuQbjN_xUj1l"
  alt="Flex box: step-4"
  width={1200}
  height={600}
/>

`flex-direction: column` property has now changed the layout to column format. Don't get confused now thinking why the boxes have gone to the starting of the container.
This is where come the property `align-items`.

## align-items

This property vertically centers the flex items within the container along the cross axis (which is usually the vertical axis when flex-direction is set to row).
Lets update our CSS and see how it changes the layout.

```css
.main {
  background-color: #1b212c;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
```

**Result:**

<Image
  src="https://drive.google.com/uc?export=view&id=18HXVA49lVEPqLV_YVQDiMB0-TRh4XT_u"
  alt="Flex box: step-5"
  width={1200}
  height={600}
/>
The boxes are now align vertically center along the `cross-axis`.

<Notes
  note="The main axis determines the direction in which the items are arranged, and the cross axis is the perpendicular direction. Understanding these axes is key to effectively using Flexbox to control layout."
  link="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_flexible_box_layout/Basic_concepts_of_flexbox"
  text="Mozilla Developer Network (MDN)"
/>

The align-items property in Flexbox has several values that control the alignment of flex items along the cross axis (which is usually the vertical axis when flex-direction is set to row). Here’s a list of all the possible values:

**flex-start**: Aligns items to the start of the cross axis (top if flex-direction is row).

**flex-end**: Aligns items to the end of the cross axis (bottom if flex-direction is row).

**center**: Centers items along the cross axis.

**baseline**: Aligns items such that their baselines align. This is particularly useful when you want text inside flex items to line up.

**stretch**: Stretches items to fill the container along the cross axis. This is the default value. If the items don't have a specific height set, they will stretch to fill the container.

Each of these properties gives you control over how flex items are aligned within their container, allowing for a wide range of layout possibilities in responsive design.

## flex-wrap

The `flex-wrap` property in Flexbox controls whether flex items are forced into a single line or allowed to wrap onto multiple lines.
Now let's see the usage of `flex-wrap` property. Try giving `2` box some `width` and see what happes. You can modify the see file like below & see.

```css
* {
  margin: 0;
}
.main {
  background-color: #1b212c;
  display: flex;
}

.box {
  background-color: #447bbe;
  color: #f8f8ff;
  font-size: 30px;
  padding: 35px;
  margin: 10px;
  width: 20px;
}

.b2 {
  width: 300px;
}
```

**Result**

<Image
  src="https://drive.google.com/uc?export=view&id=1S0T3Y7Na88sRj6avUiWem_CjRyr1ELBb"
  alt="Flex box: step-6"
  width={1200}
  height={600}
/>
You can see that when the screen size is smaller the remaining boxes are overflow
from the screen this is due to the default behaviou which sets the `flex-wrap` property
to `nowrap`;

Now, let give the container a `flex-wrap: wrap` property.

<Image
  src="https://drive.google.com/uc?export=view&id=1O3hVJPfV4GZMkwkUs0sxK6mfNXIh5gg-"
  alt="Flex box: step-6.1"
  width={1200}
  height={600}
/>
So now the boxes are not overflowing from the screen rather they are moved to the
new line.

<Notes note="You can also use a shorhand called flex-flow for setting both `flex-direction` and `flex-wrap`. Example: flex-flow: column wrap;" />

## order

Controls the order in which flex items appear in the flex container. The default is `0`, but this can be set to any integer value, positive or negative usually -1 or 1.
Lets see it in action. Apply below CSS to the `b2` box.

```css
.b2 {
  order: 1;
}
```

<Image
  src="https://drive.google.com/uc?export=view&id=1Xu0VZAkJXS_s2u1hVzYqQW0IW5jnk-HO"
  alt="order property"
  width={1200}
  height={600}
/>
The box 2 is now coming after all the items inside the container as we gave the value
as 1. Try giving it -1 and see what happens!!

## grow

Defines the ability of a flex item to grow if necessary. A value of `1` means the item will grow to fill the container, relative to the other flex items.
Add below property for b2 box and see what happens now.

```css
.b2 {
  width: 300px;
  grow: 1;
}
```

<Image
  src="https://drive.google.com/uc?export=view&id=1SQKjVV1gkbhLeZKcT0jmswdA-ATJf0nO"
  alt="grow"
  width={1200}
  height={600}
/>
Notice how box b2 is now taking all the remaining spaces.

## shrink

Defines the ability of a flex item to shrink if necessary. A value of `1` means the item can shrink, relative to the other flex items.
Lets modify the css for box b2 and see.

```css
.b2 {
  width: 300px;
  shrink: 1;
}
```

<Image
  src="https://drive.google.com/uc?export=view&id=1V5IUJKqypvf0n1ZZUbESqVWC7kyyxGG1"
  alt="shrink"
  width={1200}
  height={600}
/>
Notice how the box b2 is taking only the required space unlike `grow`. Try minimizing
the screen and see how it behaves.

<Notes note="grow controls how much a flex item can grow relative to the other flex items in the container when there is extra space available where shrink controls how much a flex item can shrink relative to the other flex items in the container when there is not enough space available." />

### `flex-basis`

Defines the default size of an element before the remaining space is distributed. It can be set to a specific size (e.g., `200px`) or `auto`.
Apply the below css to b2 box and see.

```css
.b2 {
  flex-basis: 200px;
}
```

`flex-basis: 200px;`: This sets the initial size of the .b2 flex item to 200px before any space distribution occurs based on grow or flex-shrink. This means that .b2 will attempt to take up 200px of space in the flex container. If the container has more or less space, other properties like grow and shrink will determine how the space is adjusted.

<Image
  src="https://drive.google.com/uc?export=view&id=1V5IUJKqypvf0n1ZZUbESqVWC7kyyxGG1"
  alt="flex-basis"
  width={1200}
  height={600}
/>

<Notes note="You can use a shorthand for setting `grow`, `shrink`, and `flex-basis` together with just `flex` property. Example: flex: 2 1 150px;" />

Test your learning in the below website.
<CustomLink
    text="https://flexboxfroggy.com/"
    link="https://flexboxfroggy.com/"
/>

## Conclusion

Mastering Flexbox is essential for creating responsive, flexible, and modern web layouts. By understanding properties like flex-grow, flex-shrink, flex-basis, and the shorthand flex, you can control the behavior of your elements within a container, ensuring they adapt seamlessly across different screen sizes. Whether you’re building complex grids or simple navigation bars, Flexbox provides the tools to make your designs robust and user-friendly.

For more insights and practical examples on Flexbox and other CSS techniques, stay tuned to our blog and continue refining your web development skills.
]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/Mastering Flexbox in CSS.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[How to Start Learning Web Development in 2024]]></title>
            <link>https://nishangiri.dev/blog/how-to-web-dev</link>
            <guid>https://nishangiri.dev/blog/how-to-web-dev</guid>
            <pubDate>Sat, 25 May 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Discover how to start learning web development in 2024 with our comprehensive guide. Explore the latest tools, technologies, and resources for beginners. Kickstart your career in web development today!]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-05-25" />

<Image
  src="/posts/How to Start Learning Web Development in 2024.png"
  alt="How to Start Learning Web Development in 2024"
  width={1200}
  height={600}
/>

Web development remains one of the most sought-after skills in the tech industry. Whether you're looking to switch careers or start a new hobby, 2024 is a great year to begin your journey into web development. This guide will walk you through the essential steps and provide resources to help you get started.

## Table of Contents

<TableOfContents
  items={[
    {
      text: "Step 1: Understand the Basics",
      href: "#step-1-understand-the-basics",
      subItems: [
        { text: "HTML", href: "#html" },
        { text: "CSS", href: "#css" },
        { text: "JavaScript", href: "#javascript" },
        { text: "Recommended Resources", href: "#recommended-resources" },
      ],
    },
    {
      text: "Step 2: Choose a Development Path",
      href: "#step-2-choose-a-development-path",
      subItems: [
        { text: "Front-End Development", href: "#front-end-development" },
        { text: "Back-End Development", href: "#back-end-development" },
        { text: "Full-Stack Development", href: "#full-stack-development" },
      ],
    },
    {
      text: "Step 3: Learn Front-End Development",
      href: "#step-3-learn-front-end-development",
      subItems: [
        { text: "React", href: "#react" },
        { text: "Recommended Resources", href: "#recommended-resources-1" },
      ],
    },
    {
      text: "Step 4: Learn Back-End Development",
      href: "#step-4-learn-back-end-development",
      subItems: [
        { text: "Node.js and Express.js", href: "#node-js-and-express-js" },
        { text: "Recommended Resources", href: "#recommended-resources-2" },
        { text: "Databases", href: "#databases" },
        { text: "Recommended Resources", href: "#recommended-resources-3" },
      ],
    },
    {
      text: "Step 5: Version Control with Git",
      href: "#step-5-version-control-with-git",
      subItems: [
        { text: "Git", href: "#git" },
        { text: "Recommended Resources", href: "#recommended-resources-4" },
      ],
    },
    {
      text: "Step 6: Build Projects",
      href: "#step-6-build-projects",
      subItems: [
        {
          text: "Project Ideas for Beginners",
          href: "#project-ideas-for-beginners",
        },
        { text: "Showcasing Projects", href: "#showcasing-projects" },
      ],
    },
    {
      text: "Step 7: Stay Updated and Join Communities",
      href: "#step-7-stay-updated-and-join-communities",
      subItems: [
        { text: "Recommended Communities", href: "#recommended-communities" },
        { text: "Stay Updated", href: "#stay-updated" },
      ],
    },
    { text: "Conclusion", href: "#conclusion" },
  ]}
/>

## **Step 1: Understand the Basics**

Before diving into complex frameworks and tools, it's crucial to grasp the basics of web development. These foundational skills will be the building blocks of your learning journey.

### **HTML**

HTML (HyperText Markup Language) is the standard markup language for creating web pages. It provides the structure of a webpage.

```html
<!DOCTYPE html>
<html>
  <head>
    <title>My First Web Page</title>
  </head>
  <body>
    <h1>Hello, World!</h1>
    <p>This is my first web page.</p>
  </body>
</html>
```

### **CSS**

CSS (Cascading Style Sheets) is used to style and layout web pages. It allows you to add colors, fonts, and spacing to your HTML.

```CSS
body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
  color: #333;
}

h1 {
  color: #0056b3;
}
```

## **Javascript**

JavaScript is a programming language that enables interactive web pages. It allows you to implement complex features such as dynamic content updates, multimedia controls, and animations.

```js
document.querySelector("h1").textContent = "Hello, JavaScript!";
```

## Recommended Resources

- <CustomLink text="Mozilla Developer Network (MDN)" link="https://developer.mozilla.org/en-US/" />
- <CustomLink text="freeCodeCamp" link="https://www.freecodecamp.org/" />
- <CustomLink text="W3Schools" link="https://www.w3schools.com/" />

## **Step 2: Choose a Development Path**

Web development can be broadly categorized into three paths: front-end, back-end, and full-stack development.

## **Front-End Development**

Front-end developers focus on the client-side of web applications, dealing with the layout, design, and interactivity of a site.

## Key Technologies:

- [HTML, CSS, JavaScript]
- [Frameworks: React, Vue, Angular]

## **Back-End Development**

Back-end developers work on the server-side, dealing with databases, server logic, and application architecture.

## Key Technologies:

- [Node.js, Express.js]
- [Databases: SQL (MySQL, PostgreSQL), NoSQL (MongoDB)]

## **Full-Stack Development**

Full-stack developers have the skills to work on both the front-end and back-end of web applications.

## Key Technologies:

- [Combination of front-end and back-end technologies]

## **Step 3: Learn Front-End Development**

To get started with front-end development, you need to learn HTML, CSS, and JavaScript, along with one or more front-end frameworks.

## **React**

<CustomLink text="React" link="https://react.dev/" /> is a popular JavaScript library for building user interfaces. It allows you to create reusable UI components.

```jsx
import React from "react";
import ReactDOM from "react-dom";

function App() {
  return <h1>Hello, React!</h1>;
}

ReactDOM.render(<App />, document.getElementById("root"));
```

## Recommended Resources:

- <CustomLink text="React" link="https://react.dev/" />
- <CustomLink text="Scrimba React Course" link="https://v2.scrimba.com/learn-react-c0e" />

## **Step 4: Learn Back-End Development**

To handle server-side logic and databases, you need to learn back-end technologies.

## **Node.js and Express.js**

<CustomLink text="Node.js" link="https://nodejs.org/en" /> is a JavaScript runtime built on Chrome's V8 JavaScript engine. <CustomLink text="Express.js" link="https://expressjs.com/" /> is a web application framework for Node.js.

```js
const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("Hello, Node.js and Express!");
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});
```

## Recommended Resources:

- <CustomLink text="Node.js Official Documentation" link="https://nodejs.org/en" />
- <CustomLink text="Express.js Official Documentation" link="https://expressjs.com/" />

## **Databases**

You need to understand how to work with databases to store and retrieve data.

## Key Technologies:

- [SQL: MySQL, PostgreSQL]
- [NoSQL: MongoDB]

## Recommended Resources:

- <CustomLink text="MySQL Tutorial" link="https://www.w3schools.com/MySQL/default.asp" />
- <CustomLink text="MongoDB University" link="https://learn.mongodb.com/" />

## **Step 5: Version Control with Git**

Version control is essential for tracking changes in your code and collaborating with others.

## **Git**

<CustomLink text="Git" link="https://github.com/dashboard" /> is a version control system that lets you manage and keep track of your source code history.

```Git
# Initialize a new Git repository
git init

# Add files to the staging area
git add .

# Commit changes
git commit -m "Initial commit"
```

## Recommended Resources:

- <CustomLink text="Pro Git Book" link="https://git-scm.com/book/en/v2" />
- <CustomLink text="GitHub Guides" link="https://github.com/git-guides" />

## **Step 6: Build Projects**

The best way to learn web development is by building projects. Start with simple projects and gradually move to more complex ones.

## **Project Ideas for Beginners**

- [Personal portfolio website]
- [To-do list application]
- [Weather app using a weather API]

## **Showcasing Projects**

Create a portfolio to showcase your projects. Use platforms like GitHub Pages, Netlify, or Vercel to host your projects.

## **Step 7: Stay Updated and Join Communities**

Web development is a rapidly evolving field. Stay updated with the latest trends and technologies by following blogs, joining communities, and participating in discussions.

## Recommended Communities

- <CustomLink text="Stack Overflow" link="https://stackoverflow.com/" />
- <CustomLink text="Reddit: r/webdev" link="https://www.reddit.com/" />
- <CustomLink text="Dev.to" link="https://dev.to/" />

## **Stay Updated**

- Follow web development blogs and news sites.
- Attend webinars, workshops, and conferences.

---

## Conclusion

Starting your journey in web development in 2024 is an exciting and rewarding endeavor. By following these steps and utilizing the recommended resources, you can build a solid foundation and progress to more advanced topics. Remember, consistency and practice are key to becoming a proficient web developer.

---

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/How to Start Learning Web Development in 2024.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[How I Built and Deployed Micro Frontends Using Webpack, Module Federation, Docker, and NGINX]]></title>
            <link>https://nishangiri.dev/blog/micro-frontend</link>
            <guid>https://nishangiri.dev/blog/micro-frontend</guid>
            <pubDate>Sat, 17 May 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[A step-by-step guide on how I implemented micro frontends with Webpack Module Federation, Docker, and NGINX for scalable React applications.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2025-05-17" />

<Image
  src="/posts/Webpack Micro frontend.png"
  alt="Best 7 React UI Libraries for 2024"
  width={1200}
  height={600}
/>

Micro frontends allow large teams to build and deploy independently scalable frontend applications. In this blog, I’ll walk you through how I built a micro frontend architecture using **Webpack Module Federation**, **Docker**, and **NGINX**, based on a real-world project.

---

## What Is Micro Frontend Architecture?

Micro frontends break a monolithic frontend into smaller, independently deployable pieces. Each team can own and deploy their part of the frontend.

**Example structure:**

- `mfe-host` (container app + shared components/utilities)
- `mfe1` (remote)
- `mfe2` (remote)

---

## Structuring the Repositories

```
- mfe-host/
- mfe1/
- mfe2/
```

Each MFE is an isolated React app with its own Webpack config and deployment pipeline.

---

## 🔧 Basic Webpack Setup

To better manage environment-specific configurations, we use `webpack-merge` to separate common, development, and production settings for both the Host and MFE1 apps.

First, install the dependency:

```
npm i webpack-merge
```

We’ll define three config files per app:

- `webpack.common.js`
- `webpack.dev.js`
- `webpack.prod.js`

### Host MFE Configuration

**webpack.common.js**

```js
const { ModuleFederationPlugin } = require("webpack").container;
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.js",
  resolve: { extensions: [".js", ".jsx"] },
  plugins: [
    new ModuleFederationPlugin({
      name: "mfe_host",
      remotes: {
        mfe1: "mfe1@http://localhost:3001/remoteEntry.js",
        mfe2: "mfe2@http://localhost:3002/remoteEntry.js",
      },
      shared: ["react", "react-dom"],
    }),
    new HtmlWebpackPlugin({ template: "./public/index.html" }),
  ],
};
```

**webpack.prod.js**

```js
const { merge } = require("webpack-merge");
const common = require("./webpack.common");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");

module.exports = merge(common, {
  mode: "production",
  plugins: [new MiniCssExtractPlugin({ filename: "[name].[contenthash].css" })],
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin(), new CssMinimizerPlugin()],
    splitChunks: { chunks: "all" },
  },
});
```

**webpack.dev.js**

```js
const { merge } = require("webpack-merge");
const common = require("./webpack.common");

module.exports = merge(common, {
  mode: "development",
  devServer: {
    port: 3000,
    historyApiFallback: true,
    hot: true,
  },
  devtool: "eval-source-map",
});
```

### Remote MFE1 Configuration

**webpack.common.js**

```js
const { ModuleFederationPlugin } = require("webpack").container;
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.js",
  resolve: { extensions: [".js", ".jsx"] },
  plugins: [
    new ModuleFederationPlugin({
      name: "mfe1",
      filename: "remoteEntry.js",
      exposes: {
        "./Page": "./src/pages/Page",
      },
      shared: ["react", "react-dom"],
    }),
    new HtmlWebpackPlugin({ template: "./public/index.html" }),
  ],
};
```

**webpack.prod.js**

```js
const { merge } = require("webpack-merge");
const common = require("./webpack.common");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");

module.exports = merge(common, {
  mode: "production",
  plugins: [new MiniCssExtractPlugin({ filename: "[name].[contenthash].css" })],
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin(), new CssMinimizerPlugin()],
    splitChunks: { chunks: "all" },
  },
});
```

**webpack.dev.js**

```js
const { merge } = require("webpack-merge");
const common = require("./webpack.common");

module.exports = merge(common, {
  mode: "development",
  devServer: {
    port: 3001,
    historyApiFallback: true,
    hot: true,
  },
  devtool: "eval-source-map",
});
```

## 🌍 Using Environment Variables Across Environments

You’ll often want different values for API endpoints, feature flags, or keys in local, dev, and production environments.

### Step 1: Create `.env` files in each project root

```

.env.development
.env.production
.env.local

```

Example content for `.env.development`:

```bash
REACT_APP_API_URL=http://localhost:4000
```

### Step 2: Install dotenv plugin (for custom Webpack)

```bash
npm install dotenv-webpack --save-dev
```

### Step 3: Configure in Webpack

```js
const Dotenv = require("dotenv-webpack");

plugins: [new Dotenv({ path: "./.env.development" })];
```

Alternatively, in Create React App (CRA), variables prefixed with `REACT_APP_` are auto-injected.

> ⚠️ Never include sensitive data like secrets or tokens in these files.

---

### Environment-Specific Execution

To specify environment files dynamically in your commands, you can set the `DOTENV_CONFIG_PATH`:

```bash
npm install dotenv-cli --save-dev
```

Then update scripts like this:

```json
"scripts": {
  "start:dev": "dotenv -e .env.development -- webpack serve --config webpack.dev.js",
  "start:prod": "dotenv -e .env.production -- webpack --config webpack.prod.js",
  "build:dev": "dotenv -e .env.development -- webpack --config webpack.dev.js",
  "build:prod": "dotenv -e .env.production -- webpack --config webpack.prod.js"
}
```

This ensures the right environment variables are injected based on the context of the command.

---

## 🐳 Basic Docker Setup

**Dockerfile**

```Dockerfile
FROM node:18 AS build
WORKDIR /app
COPY . .
RUN npm install && npm run build

FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
```

**Build & Run**

```bash
docker build -t mfe1 .
docker run -d -p 3001:80 mfe1
```

---

## 🌐 Basic NGINX Configuration

```nginx
server {
  listen 80;
  server_name localhost;

  location / {
    root /usr/share/nginx/html;
    index index.html;
  }

  location /remoteEntry.js {
    add_header Cache-Control "no-cache";
  }
}
```

## 🔌 Essential Webpack Plugins

```js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

plugins: [
  new HtmlWebpackPlugin({ template: "./public/index.html" }),
  new CleanWebpackPlugin(),
];
```

---

## 🚀 Production Optimization Techniques

```js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const webpack = require('webpack');

plugins: [
  new MiniCssExtractPlugin({ filename: '[name].[contenthash].css' }),
  new CompressionPlugin({ algorithm: 'gzip' }),
  new BundleAnalyzerPlugin({ analyzerMode: 'static', openAnalyzer: false }),
  new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }),
  new webpack.IgnorePlugin({ resourceRegExp: /^\.\/locale$/, contextRegExp: /moment$/ }),
  new webpack.optimize.ModuleConcatenationPlugin(),
];

optimization: {
  minimize: true,
  minimizer: [new TerserPlugin(), new CssMinimizerPlugin()],
  splitChunks: { chunks: 'all' },
};
```

---

## ✅ Conclusion

Start with a working micro frontend setup, then incrementally layer in optimizations to make it production-grade. From module federation to caching strategies and bundling best practices—each part matters.

<Notes note="This is a initial explanation that i tried to put in an article, I'll be updating it with more details and code block in the future. Stay tuned for more!" />
]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/Webpack Micro frontend.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[React 19: Features, Updates, and How to Upgrade Your React Apps]]></title>
            <link>https://nishangiri.dev/blog/react-19-release-notes</link>
            <guid>https://nishangiri.dev/blog/react-19-release-notes</guid>
            <pubDate>Sun, 08 Dec 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Discover React 19's latest features, including Actions, Server Components, new hooks, and the React Compiler. Learn how these updates improve performance, enhance SEO, and simplify React development.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-11-16" />
<Image
  src="/posts/React 19.png"
  alt="React 19 features and updates overview"
  width={1200}
  height={600}
/>
The React team has launched **React 19**, bringing powerful features to enhance
performance, simplify development, and improve user experience. This release is
packed with tools that streamline building modern web apps while keeping React
as intuitive as ever.

If you’re a developer working with **ReactJS**, **React Server Components**, or looking to improve your **React app performance**, this guide will walk you through everything React 19 offers.

---

## 🚀 **What’s New in React 19?**

### 1. **Introducing Actions: Simplifying State and Data Mutations**

One of the standout features in React 19 is **Actions**, designed to make **asynchronous operations** like form submissions and data mutations easier.

**Why Actions are game-changing:**

- No need for manual state management during async operations.
- Automatically handles loading states, errors, and optimistic updates (i.e., showing the update before server confirmation).

Here’s an example:

```javascript
"use client";

import { useFormStatus } from "react";

function SubmitButton() {
  const { pending } = useFormStatus();
  return <button disabled={pending}>Submit</button>;
}
```

With Actions, React takes care of everything behind the scenes, saving you from repetitive code.

## 2. Server Components: Better Performance, Less JavaScript

React 19 doubles down on **Server Components**, allowing parts of your UI to render on the server. This reduces the JavaScript sent to users, improving:

- **Initial page load speed.**
- **SEO performance**, as server-rendered content is crawler-friendly.
- **User experience**, with lighter apps and faster interactions.

Use **Server Components** for pages that fetch data or display static content to boost both speed and SEO rankings.

---

## 3. New Hooks for Better Form Management

React 19 introduces **new hooks** to make form and state management more powerful and developer-friendly:

- **`useFormStatus`**: Keeps track of form submission status (e.g., loading or error states).
- **`useFormState`**: Access the live state of your form fields to build dynamic forms.
- **`useOptimistic`**: Enables optimistic UI updates, letting you show updates instantly without waiting for server responses.

These hooks are must-haves for apps with forms or dynamic user inputs.

---

## 4. React Compiler: Boosting Performance Automatically

The **React Compiler** is a new addition that optimizes your React code automatically, making your apps faster and reducing the need for manual performance tweaks like memoization.

**What it means for you:**

- **Faster apps out of the box.**
- **Less time spent debugging performance bottlenecks.**

---

## 5. Improved Web Components Support

React 19 enhances support for **Web Components**, making it easier to integrate **custom elements** into your React projects. This is perfect for teams working with **micro frontends** or hybrid apps.

---

## 6. Simplified Metadata Management

Managing **SEO metadata** like `<title>` and `<meta>` tags is now simpler with React 19. Whether it’s dynamic page titles or meta descriptions, this feature makes your app SEO-friendly with less effort.

---

## 7. Smarter Asset Loading

React 19 introduces smarter **asset loading** to improve page transitions. Background loading ensures your app remains smooth and responsive, even on slower networks.

## 🛠️ **Upgrading to React 19**

Upgrading to React 19 is straightforward, especially if you're already using React 18.

### Steps to Upgrade:

1. Update React and React DOM:

```bash
npm install react@19 react-dom@19
```

2. Check for deprecated APIs using React 18.3, which highlights issues before upgrading.
3. Fix any warnings flagged during the upgrade process.
   Make sure to test your application thoroughly after upgrading to avoid runtime issues.

## 🌟 Why React 19 Is a Big Deal

React 19 focuses on making developers' lives easier while enhancing app performance. Here’s why it matters:

- **For Developers**: New features like Actions and hooks simplify code and reduce boilerplate.
- **For Users**: Server Components and asset loading make apps faster and more reliable.
- **For SEO**: Better metadata handling and server rendering improve search rankings.

## 💡 Final Thoughts

React 19 is a testament to the React team’s commitment to simplifying development while delivering high-performance apps. Whether you’re an experienced developer or just starting out with React, this update offers tools to build faster, smarter, and more scalable applications.

For more React and web development insights, explore [my blog](https://nishangiri.dev/blog).

Learn more on this topic on offical release notes: <CustomLink text="react.dev" link="https://react.dev/blog/2024/12/05/react-19" />
]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/React 19.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[React Server Components Explained: Benefits and Implementation]]></title>
            <link>https://nishangiri.dev/blog/react-server-component</link>
            <guid>https://nishangiri.dev/blog/react-server-component</guid>
            <pubDate>Mon, 01 Jul 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Explore React Server Components and their impact on web applications. Learn about their benefits, setup, and use cases in this in-depth article.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-07-01" />

<Image 
  src="/posts/React Server Components.png" 
  alt="React Server Components Explained: Benefits and Implementation" 
  width={1200} 
  height={600} 
/>

React Server Components (RSCs) are an exciting new feature in the React ecosystem, designed to enhance the performance and user experience of web applications. By enabling server-side rendering of components, RSCs allow developers to build faster and more efficient applications. In this guide, we'll explore what React Server Components are, how they work, their benefits, and how to implement them in your projects.

### Table of Contents

<TableOfContents items={[
  { text: 'What Are React Server Components?', href: '#what-are-react-server-components' },
  { text: 'Key Differences from Traditional React Components', href: '#key-differences-from-traditional-react-components' },
  { text: 'How React Server Components Work?', href: '#how-react-server-components-work' },
  { text: 'Benefits of React Server Components', href: '#benefits-of-react-server-components', subItems: [
    { text: 'Improved Performance', href: '#improved-performance' },
    { text: 'Enhanced SEO Capabilities', href: '#enhanced-seo-capabilities' },
    { text: 'Reduced Client-Side JavaScript Bundle Size', href: '#reduced-client-side-javascript-bundle-size' },
    { text: 'Faster Initial Load Times', href: '#faster-initial-load-times' }
  ]},
  { text: 'Practical Example: Rendering a Product List', href: '#practical-example-rendering-a-product-list', subItems: [
    { text: 'Prerequisites', href: '#prerequisites' },
    { text: 'Example', href: '#example' },
    { text: 'Explanation', href: '#explanation' }
  ]},
  { text: 'Best Practices for Using React Server Components', href: '#best-practices-for-using-react-server-components', subItems: [
    { text: 'Tips for Optimal Performance and Maintainability', href: '#tips-for-optimal-performance-and-maintainability' },
    { text: 'Common Pitfalls to Avoid', href: '#common-pitfalls-to-avoid' }
  ]},
  { text: 'Practical Use Cases for React Server Components', href: '#practical-use-cases-for-react-server-components', subItems: [
    { text: 'Scenarios Where RSCs Can Be Particularly Beneficial', href: '#scenarios-where-rscs-can-be-particularly-beneficial' },
    { text: 'Real-World Examples and Case Studies', href: '#real-world-examples-and-case-studies' }
  ]},
  { text: 'Performance and SEO Improvements with React Server Components', href: '#performance-and-seo-improvements-with-react-server-components', subItems: [
    { text: 'How RSCs Enhance Web Application Performance', href: '#how-rscs-enhance-web-application-performance' },
    { text: 'SEO Advantages of Using RSCs', href: '#seo-advantages-of-using-rscs' },
    { text: 'Comparison with Other Rendering Techniques', href: '#comparison-with-other-rendering-techniques' }
  ]},
  { text: 'Conclusion', href: '#conclusion' },
]} />
---
## What Are React Server Components?
React Server Components (RSCs) are a new type of component that allows React applications to render parts of the UI on the server rather than on the client. This means that certain components can be processed and rendered by the server and then sent to the client as fully-rendered HTML. This approach can significantly improve performance and user experience.

## Key Differences from Traditional React Components
**1. Server-Side Rendering**: Unlike traditional components, RSCs are rendered on the server.

**2. No Client-Side JavaScript**: RSCs don't include JavaScript that runs on the client, reducing the client-side bundle size.

**3. Improved Performance**: By offloading rendering to the server, RSCs can improve initial load times and SEO.

## How React Server Components Work?

RSCs work by splitting the rendering process between the server and the client. Here's a simplified workflow:

**1. Request Handling**: The client makes a request to the server.

**2. Server-Side Rendering**: The server processes the request and renders the necessary components as HTML.

**3. Sending HTML to Client**: The server sends the fully-rendered HTML to the client.

**4. Client-Side Hydration**: The client receives the HTML and hydrates it with client-side interactivity.

This process helps in delivering a faster and more efficient user experience.

## Benefits of React Server Components

**1. Improved Performance**
By rendering components on the server, RSCs reduce the amount of JavaScript that needs to be processed on the client, leading to faster load times and a smoother user experience.

**2. Enhanced SEO Capabilities**
Since the HTML is fully rendered on the server before being sent to the client, search engines can more easily crawl and index the content, improving SEO.

**3. Reduced Client-Side JavaScript Bundle Size**
RSCs help minimize the amount of JavaScript sent to the client, which reduces the overall bundle size and improves loading times.

**4. Faster Initial Load Times**
With server-side rendering, the initial page load is faster because the client receives fully-rendered HTML instead of needing to render it from scratch.

## Practical Example: Rendering a Product List
To illustrate the benefits and usage of React Server Components, let's create a simple example where we render a list of products fetched from an API. This example will show how RSCs can be used to enhance performance and SEO.

#### Prerequisites

Before you begin, ensure you have the following:

- <CustomLink text="Node.js" link="https://nodejs.org/en"/> installed
- A React application setup

### Example

1. **Create a Server Component to Fetch and Render Products:**
    ```jsx
    // src/components/ProductList.server.js
    import React, { useEffect, useState } from 'react';

    const ProductList = () => {
      const [products, setProducts] = useState([]);

      useEffect(() => {
        async function fetchProducts() {
          const response = await fetch('https://api.example.com/products');
          const data = await response.json();
          setProducts(data);
        }

        fetchProducts();
      }, []);

      return (
        <div>
          <h1>Product List</h1>
          <ul>
            {products.map((product) => (
              <li key={product.id}>{product.name}</li>
            ))}
          </ul>
        </div>
      );
    };

    export default ProductList;
    ```
    
2. **Update Your Server to Handle RSCs:**
    ```jsx
        // server.js
    import express from 'express';
    import React from 'react';
    import ReactDOMServer from 'react-dom/server';
    import ProductList from './src/components/ProductList.server';

    const app = express();

    app.get('/', (req, res) => {
      const content = ReactDOMServer.renderToString(<ProductList />);
      res.send(`<!DOCTYPE html><html><body>${content}</body></html>`);
    });

    app.listen(3000, () => console.log('Server running on port 3000'));
    ```

### Explanation
- **ProductList Component**: This server component fetches a list of products from an API and renders it as an HTML list. The useEffect hook ensures that the data is fetched when the component is rendered on the server.
- **Server Setup**: The server uses Express to handle requests. When a request is made to the root URL, it renders the ProductList component to a string and sends it as the response.

## Best Practices for Using React Server Components

### Tips for Optimal Performance and Maintainability

1. **Keep Server Components Simple**: Focus on rendering and avoid client-side logic.

2. **Minimize Data Fetching in Server Components**: Fetch data before rendering the component.

3. **Use Server Components for Heavy Lifting**: Delegate complex rendering tasks to the server.

### Common Pitfalls to Avoid
1. **Mixing Server and Client Components**: Keep server and client components separate to avoid confusion.

2. **Overusing Server Components**: Use server components selectively for performance-critical parts of the application.

## Practical Use Cases for React Server Components

### Scenarios Where RSCs Can Be Particularly Beneficial

1. **Content-Heavy Websites**: Blogs, news sites, and e-commerce platforms can benefit from faster load times and improved SEO.

2. **Dashboard Applications**: Complex dashboards can offload heavy rendering tasks to the server, enhancing performance.

3. **Static Site Generation**: Generate static pages with dynamic content, combining the benefits of SSR and static site generation.

### Real-World Examples and Case Studies
1. **E-commerce Platforms**: Faster product page loads can lead to better user engagement and higher conversion rates.
2. **News Websites**: Quick loading articles improve reader retention and SEO ranking.

## Performance and SEO Improvements with React Server Components
### How RSCs Enhance Web Application Performance?
By rendering on the server, RSCs reduce the client's processing load, leading to faster initial page loads and smoother transitions.

### SEO Advantages of Using RSCs
Fully-rendered HTML improves crawlability and indexability by search engines, resulting in better SEO performance compared to client-rendered pages.

### Comparison with Other Rendering Techniques
- **Client-Side Rendering (CSR)**: RSCs offer better performance and SEO than CSR.

- **Static Site Generation (SSG)**: RSCs provide more flexibility and dynamic content handling than SSG.

## Conclusion
React Server Components (RSCs) represent a significant advancement in the React ecosystem, offering remarkable benefits in terms of performance and SEO. By leveraging server-side rendering, RSCs enable faster load times, reduced client-side JavaScript, and enhanced search engine visibility. These benefits make RSCs an invaluable tool for building modern, high-performance web applications.

As web development continues to evolve, understanding and utilizing technologies like React Server Components will be crucial for creating applications that are not only efficient but also provide an exceptional user experience. Whether you're working on content-heavy websites, complex dashboards, or static site generation, RSCs offer a versatile solution to many performance challenges.

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/React Server Components.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[How to Build a Dynamic Star Rating Component in React: Step-by-Step Guide]]></title>
            <link>https://nishangiri.dev/blog/react-star-rating</link>
            <guid>https://nishangiri.dev/blog/react-star-rating</guid>
            <pubDate>Sat, 16 Nov 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn how to build a dynamic star rating component in React step by step. Perfect for beginners and essential for React projects and interviews. Includes code snippets and examples!]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-11-16" />
<Image
  src="/posts/Star Rating.png"
  alt="Star Rating Component in React: Step-by-Step Guide"
  width={1200}
  height={600}
/>

Star rating components are common in modern web apps and make it easy to collect user feedback. Whether you’re shopping online, reviewing a restaurant, or rating an app, star ratings offer a simple and clear way for users to share their opinions. It's also an important feature to implement in React for interviews and real-world projects. Let's jump into building a React star rating component step by step.

## What we'll be building

**Follow the step by step implementation below or Get the code directly from my sandbox (Thank me later..🤭)**

<SandboxEmbed
  src="https://codesandbox.io/embed/g54kxc?view=preview&module=%2Fsrc%2FStarRating.js"
  title="star-rating-react"
/>

**I am asuming that you have the bolier plate steup for a react application with <CustomLink text="create-react-app" link="https://create-react-app.dev/"/>.**

## Step 1: Install react-icons for React Star Rating Component

First, we need to install the <CustomLink text="react-icons" link="https://www.npmjs.com/package/react-icons"/> library to access star icons for our rating component. Run the following command in your terminal:

```bash
npm install react-icons --save
```

## Step 2: Create the StarRating Component

Next, create a new file named StarRating.js and add the following code. This component uses state to manage the selected rating and hover effect.

### Code Example: React Star Rating Component

```js
import { useState } from "react";
import { FaStar } from "react-icons/fa";

export default function StarRating() {
  const [selected, setSelected] = useState(0); // State variable to store selected rating
  const [hover, setHover] = useState(0); // State variable to store hover state

  return (
    <section className="container">
      <h2>How was your experience?</h2>
      <div className="star-rating">
        {/* Mapping an array with values 1 to 5 */}
        {[1, 2, 3, 4, 5].map((num) => (
          <FaStar
            key={num}
            onClick={() => setSelected(num)} // Set selected rating
            onMouseOver={() => setHover(num)} // Track hover state
            onMouseLeave={() => setHover(selected)} // Reset hover to selected on mouse leave
            size={50}
            color={num <= hover ? "orange" : "grey"} // Highlight stars on hover or selection
          />
        ))}
      </div>
      <h2>Rating: {hover}</h2>
    </section>
  );
}
```

## Step 3: Add CSS for Styling

To style the star rating component, add the following CSS code to styles.css:

```css
/* Removing default styles */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.App {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  justify-content: center;
  align-items: center;
}

.star-rating {
  cursor: pointer;
}
```

## Step 4: Import and Use the StarRating Component

Finally, import the StarRating component into your App.js file and render it:

```js
import StarRating from "./StarRating";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <StarRating />
    </div>
  );
}
```

## Conclusion

Now that you’ve built a functional React star rating component, challenge yourself by adding more features like half-star ratings or animations.
]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/Star Rating.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Implementing Dark Mode in React JS with Tailwind CSS]]></title>
            <link>https://nishangiri.dev/blog/react-tailwindcss-darkmode</link>
            <guid>https://nishangiri.dev/blog/react-tailwindcss-darkmode</guid>
            <pubDate>Sat, 01 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Want to give your React JS app a sleek dark mode? This guide shows you how to do it using Tailwind CSS. Follow our easy, step-by-step instructions to enhance your app’s user experience]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-06-01" />

<Image 
  src="/posts/Implementing Dark Mode in React JS wi_th Tailwind CSS.png" 
  alt="How to implement Dark Mode in React JS with Tailwind CSS" 
  width={1200} 
  height={600} 
/>

Dark mode has surged in popularity among web users and developers alike, providing a sleek and modern interface option that is both visually appealing and easier on the eyes, particularly in low-light environments. For web developers working with <CustomLink text="React" link="https://react.dev/" /> and <CustomLink text="Tailwind CSS" link="https://tailwindcss.com/" />, implementing dark mode can enhance the user experience by offering a customizable and energy-efficient display alternative. In this guide, we will explore the steps to integrate dark mode into your React JS application using Tailwind CSS. From setting up your project to creating a functional toggle switch, applying responsive dark mode styles, and ensuring user preferences are saved, this tutorial covers all you need to know. Whether you're looking to modernize your existing application or build a new project, this guide will help you leverage dark mode to create a more engaging and user-friendly web experience.

## Table of Contents

<TableOfContents items={[
  { text: 'Why Dark Mode?', href: '#why-dark-mode' },
  { text: 'Setting Up the Project', href: '#setting-up-the-project' },
  { text: 'Creating a New React Project', href: '#creating-a-new-react-project' },
  { text: 'Installing Tailwind CSS', href: '#installing-tailwind-css' },
  { text: 'Implementing Dark Mode', href: '#implementing-dark-mode' },
  { text: 'Creating the Toggle Switch', href: '#creating-the-toggle-switch' },
  { text: 'Applying Dark Mode Styles with Tailwind CSS', href: '#applying-dark-mode-styles-with-tailwind-css' },
  { text: 'Persisting User Preferences', href: '#persisting-user-preferences' },
  { text: 'Best Practices for Dark Mode Design', href: '#best-practices-for-dark-mode-design' },
  { text: 'Conclusion', href: '#conclusion' },
  { text: 'FAQs', href: '#faqs' }
]} />

## Why Dark Mode?

Dark mode offers several benefits:

- **Reduces Eye Strain:** Especially in low-light conditions, dark mode can help reduce eye strain and fatigue, providing a more comfortable reading experience.
- **Energy Efficiency:** Saves battery life on OLED and AMOLED screens, as these screens consume less power when displaying dark colors.
- **Aesthetic Appeal:** Provides a modern, sleek look that can enhance the visual appeal of your application and cater to user preferences.

## Setting Up the Project

### Creating a New React Project

First, let's create a new React project using Create React App. Open your terminal and run:

```terminal
npx create-react-app dark-mode-app
cd dark-mode-app
```

Create React App is a convenient way to set up a new React project with all the necessary configurations and dependencies.

### Installing Tailwind CSS

Next, we need to install <CustomLink text="Tailwind CSS" link="https://tailwindcss.com/" />. Follow these steps to set it up in your React project:

1. **Install Tailwind CSS via npm:**

```terminal
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
```

This command installs Tailwind CSS along with its dependencies and initializes the configuration files.

2. **Configure Tailwind CSS:**
   In `tailwind.config.js`, enable dark mode by setting it to 'class':

```jsx
module.exports = {
  darkMode: "class", // Enable dark mode via class strategy
  content: ["./src/**/*.{js,jsx,ts,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};
```

This configuration allows you to apply dark mode styles conditionally using a CSS class.

3. **Add Tailwind to CSS:**
   In `src/index.css`, add the following lines:

```CSS
@tailwind base;
@tailwind components;
@tailwind utilities;
```

These lines import Tailwind CSS’s base, components, and utilities styles into your project.

## Implementing Dark Mode

### Creating the Toggle Switch

We'll create a toggle switch to enable users to switch between light and dark modes.

1. **Create a Toggle Component:**
   Create a new file `src/components/ThemeToggle.js`:

```jsx
import React, { useState, useEffect } from "react";

const ThemeToggle = () => {
  const [theme, setTheme] = useState("light");

  useEffect(() => {
    if (
      localStorage.getItem("theme") === "dark" ||
      (!("theme" in localStorage) &&
        window.matchMedia("(prefers-color-scheme: dark)").matches)
    ) {
      document.documentElement.classList.add("dark");
      setTheme("dark");
    } else {
      document.documentElement.classList.remove("dark");
      setTheme("light");
    }
  }, []);

  const toggleTheme = () => {
    if (theme === "dark") {
      document.documentElement.classList.remove("dark");
      localStorage.setItem("theme", "light");
      setTheme("light");
    } else {
      document.documentElement.classList.add("dark");
      localStorage.setItem("theme", "dark");
      setTheme("dark");
    }
  };

  return (
    <button
      onClick={toggleTheme}
      className="bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 px-4 py-2 rounded"
    >
      {theme === "dark" ? "Switch to Light Mode" : "Switch to Dark Mode"}
    </button>
  );
};

export default ThemeToggle;
```

This component uses `useState` and `useEffect` hooks to manage and persist the theme state.

### Applying Dark Mode Styles with Tailwind CSS

Now, let's apply dark mode styles using Tailwind CSS.

1. **Modify App Component:**
   In `src/App.js`, import and use the `ThemeToggle` component:

```jsx
import React from "react";
import ThemeToggle from "./components/ThemeToggle";

function App() {
  return (
    <div className="min-h-screen bg-white dark:bg-gray-900 text-black dark:text-white">
      <header className="p-4">
        <h1 className="text-2xl">Dark Mode in React with Tailwind CSS</h1>
        <ThemeToggle />
      </header>
      <main className="p-4">
        <p>Welcome to the dark mode demo.</p>
      </main>
    </div>
  );
}

export default App;
```

Here, we use Tailwind CSS classes to apply different styles for light and dark modes.

2. **Style the App:**
   Use Tailwind CSS classes to style the app and ensure that dark mode styles are applied:

```CSS
/* In src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

/* Custom styles if necessary */
```

This ensures that your styles are correctly applied and that the dark mode styles are activated when the dark mode class is added.

### Persisting User Preferences

Ensure that the user's dark mode preference is saved and applied on subsequent visits.

1. **Update ThemeToggle Component:**
   The component already includes logic to save and load the theme preference using `localStorage`.

## Best Practices for Dark Mode Design

- **Color Contrast:** Ensure sufficient contrast between text and background colors for readability. A common mistake is using colors that are too similar, which can strain users' eyes. Tools like the <CustomLink text="WebAIM contrast checker" link="https://webaim.org/resources/contrastchecker/"/> can help you ensure your color choices meet accessibility standards.
- **Consistent Icons:** Use consistent iconography that adapts to both light and dark themes. Icons should be clearly visible in both modes, which might require using different icon sets or colors.
- **Accessible Design:** Test your design with accessibility tools to ensure it meets standards. Consider using ARIA (Accessible Rich Internet Applications) attributes to improve navigation and readability for screen readers.

## Conclusion

Implementing dark mode in your React JS project using Tailwind CSS is straightforward and enhances user experience. By following this guide, you can create a visually appealing and functional dark mode feature for your web applications. Dark mode not only modernizes the look of your application but also caters to user preferences and accessibility needs.

### Additional Resources

- <CustomLink text="Tailwind CSS Documentation" link="https://tailwindcss.com/docs"/>
- <CustomLink text="React JS Documentation" link="https://reactjs.org/docs/getting-started.htm"/>
- <CustomLink text="WebAIM Contrast Checker" link="https://webaim.org/resources/contrastchecker/"/>

By implementing these steps, you ensure that your application is up-to-date with current web development trends and provides a better user experience. If you have any questions or need further assistance, feel free to leave a comment below.

## FAQs

### How do I enable dark mode in React JS using Tailwind CSS?

To enable dark mode in React JS using Tailwind CSS, you need to set the `darkMode` option to 'class' in the `tailwind.config.js` file. Then, create a toggle component to switch between light and dark modes by adding or removing the 'dark' class to the root element.

### Can I use Tailwind CSS to apply dark mode styles conditionally?

Yes, Tailwind CSS allows you to apply dark mode styles conditionally by using the `dark:` prefix. For example, `dark:bg-gray-900` will apply the `bg-gray-900` class when dark mode is enabled.

### How can I save user preferences for dark mode in a React JS application?

You can save user preferences for dark mode using the `localStorage`

### What are some best practices for designing a dark mode interface?

Best practices for designing a dark mode interface include ensuring sufficient color contrast, using the consistent icon

**Happy Coding!** 😊
]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/Implementing Dark Mode in React JS wi_th Tailwind CSS.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[React vs Next.js: Choosing the Right Framework for Your Next Project]]></title>
            <link>https://nishangiri.dev/blog/reactvsnextjs</link>
            <guid>https://nishangiri.dev/blog/reactvsnextjs</guid>
            <pubDate>Thu, 30 May 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Discover the key differences between React and Next.js to choose the right framework for your next project. Explore features, performance, SEO benefits, and use cases to make an informed decision.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-05-30" />

<Image 
  src="/posts/React vs Next.js Choosing the Right Framework for Your Next Project.png"
  alt="React vs Next.js Choosing the Right Framework for Your Next Project" 
  width={1200} 
  height={600} 
/>

In web development, picking the right framework is crucial for your project's success. Among the many options available, React and Next.js are two of the most popular and powerful tools. React, developed by Facebook, is a versatile JavaScript library for building user interfaces. NextJs, created by Vercel, is a robust framework built on top of React that offers server-side rendering and static site generation.

Understanding the details of each can help developers make an informed decision that aligns with their project’s goals and performance needs. In this guide, we'll explore the core features, strengths, and use cases of React and Next.js. We'll provide a clear comparison to help you decide which framework is best for your next project.

## Table of Contents

<TableOfContents items={[
  { text: 'Understanding React', href: '#understanding-react' },
  { text: 'Understanding Next.js', href: '#understanding-next-js' },
  { text: 'Key Differences Between React and Next.js', href: '#key-differences-between-react-and-next-js' },
  { text: 'Use Cases and Project Suitability', href: '#use-cases-and-project-suitability' },
  { text: 'Performance Comparison', href: '#performance-comparison' },
  { text: 'Developer Experience', href: '#developer-experience' },
  { text: 'Community and Support', href: '#community-and-support' },
  { text: 'Conclusion: Which Framework Should You Choose?', href: '#conclusion-which-framework-should-you-choose' },
  { text: 'FAQs', href: '#faqs' }
]} />

## Understanding React

### What is React?

<CustomLink text="React" link="https://react.dev/" /> is a JavaScript library developed by Facebook for building user interfaces, especially single-page applications (SPAs). It allows developers to create reusable UI components, making development more efficient and manageable.

### Core Features of React

- **Component-Based Architecture:** React's component-based structure allows developers to build encapsulated components that manage their state.
- **Virtual DOM:** React uses a virtual DOM to optimize updates, leading to faster rendering and a smoother user experience.
- **Unidirectional Data Flow:** Data in React flows in one direction, making it easier to understand and debug applications.

### Pros and Cons of React
<Table
  headers={['Pros', 'Cons']}
  rows={[
    ['Reusable Components: React promotes the creation of encapsulated components that can be reused throughout the application. This modular approach simplifies development and maintenance, allowing for faster updates and consistency across the project.',
     'Complex Setup and Configuration: Setting up a React project often requires configuring tools like Webpack and Babel, which can be daunting for beginners. Managing build processes and integrating various libraries can add to the complexity.'],
    ['Virtual DOM: React’s virtual DOM improves performance by minimizing direct interactions with the actual DOM. It efficiently updates only the parts of the DOM that have changed, resulting in faster rendering and a smoother user experience.',
     'Steep Learning Curve: Learning React involves understanding its concepts, such as JSX, virtual DOM, and component lifecycle methods. These can be challenging for beginners, particularly those new to JavaScript frameworks.'],
    ['Strong Ecosystem: React has a vast ecosystem of libraries and tools for various functionalities, such as state management (Redux), routing (React Router), and testing (Jest). This extensive ecosystem allows developers to find solutions for almost any requirement.',
     'Client-Side Rendering Limitations: React primarily relies on client-side rendering, which can lead to slower initial page loads and potential SEO challenges. Additional tools and configurations are needed to implement server-side rendering.'],
    ['Large Community Support: React has a large and active community that contributes to its growth and provides extensive resources, tutorials, and third-party libraries. This support makes it easier for developers to find help and improve their skills.',
     ''],
  ]}
/>

## Understanding Next JS

### What is Next.js?

<CustomLink text="NextJs" link="https://nextjs.org/" />, developed by Vercel, is a React framework that enables server-side rendering (SSR) and static site generation (SSG). It simplifies the development of complex applications by offering a comprehensive solution with built-in features.

### Core Features of Next.js

- **Server-Side Rendering (SSR):** Next.js can render pages on the server, enhancing performance and SEO.
- **Static Site Generation (SSG):** Pre-render pages at build time, providing faster load times.
- **API Routes:** Create API endpoints within your Next.js application.
- **Built-in CSS and Sass Support:** Seamlessly integrate CSS and Sass without additional configuration.

### Pros and Cons of Next.js

<Table
  headers={['Pros', 'Cons']}
  rows={[
    ['Server-Side Rendering (SSR) and Static Site Generation (SSG): Next.js offers built-in support for SSR and SSG, which significantly improve performance and SEO. SSR renders pages on the server, providing fully rendered HTML to the client, while SSG generates static HTML pages at build time.',
    'Steeper Learning Curve: While Next.js builds on React, it introduces additional concepts such as SSR, SSG, and API routes. These features can be complex for developers who are not familiar with server-side technologies.'],
    ['Built-In Routing: Next.js provides a file-based routing system out of the box, which simplifies navigation setup. Each page is represented by a file in the `pages` directory, making routing intuitive and easy to manage.',
    'Opinionated Structure: Next.js enforces a specific project structure and conventions, which may limit flexibility. This opinionated approach can be restrictive for developers who prefer more control over their project setup.'],
    ['Performance Optimization: Next.js includes features like automatic code-splitting, which loads only the necessary code for each page, reducing load times and improving performance. It also supports optimized image loading and prefetching.',
    'Complexity in Advanced Features: Implementing advanced features like custom server logic and complex routing can be challenging in Next.js. While the framework simplifies many tasks, it can also add complexity when customizing beyond the built-in capabilities.'],
    ['SEO Benefits: By rendering pages on the server and delivering fully rendered HTML, Next.js enhances SEO. Search engines can easily crawl and index the content, leading to better search engine rankings.',
    'Smaller Community: Although growing rapidly, Next.js has a smaller community compared to React. This can mean fewer resources, libraries, and community support options available for developers.']
  ]}
/>

## Key Differences Between React and Next JS

**Rendering Mechanisms:**

- **React:** Primarily relies on client-side rendering (CSR), which means the browser handles most of the work, potentially leading to slower initial load times.
- **Next.js:** Supports server-side rendering (SSR) and static site generation (SSG), providing faster initial page loads and better SEO. This difference makes Next.js ideal for performance-critical applications and SEO-friendly sites.

**Routing:**

- **React:** Uses libraries like React Router for client-side routing, which requires additional setup and configuration.
- **Next.js:** Offers built-in file-based routing, simplifying navigation setup and reducing boilerplate code.

## Use Cases and Project Suitability

**React:**

- Ideal for single-page applications (SPAs), dynamic web applications, and projects requiring high customization.

**Next.js:**

- Best suited for static websites, e-commerce sites, SEO-focused projects, and applications needing server-side rendering.

## Performance Comparison

**React:**

- Performance largely depends on how well the developer optimizes the application.

**Next.js:**

- Offers enhanced performance through SSR and SSG, leading to faster initial load times and better SEO.

## Developer Experience

**Learning Curve:**

- **React:** Steeper learning curve, but offers great flexibility once mastered.
- **Next.js:** Easier setup and structure, but requires understanding SSR and SSG.

**Tooling and Ecosystem:**

- **React:** Vast ecosystem with numerous libraries and tools.
- **Next.js:** Provides many built-in features and integrates seamlessly with the React ecosystem.

## Community and Support

**React:**

- Large and active community, extensive documentation, numerous tutorials and resources.

**Next.js:**

- Growing community, strong support from Vercel, comprehensive documentation, and learning resources.

## Conclusion: Which Framework Should You Choose?

In summary, both React and Next.js are powerful tools with distinct advantages. Your choice depends on your project requirements:

- **Choose React** if you need flexibility and are building a highly dynamic, single-page application.
- **Choose Next.js** if you want a simplified setup, better performance, and improved SEO for your project.

Assess your specific needs and project goals to make the best decision.

## FAQs

### Is Next.js better than React?

- It depends on your project needs. Next.js is better for projects requiring server-side rendering, static site generation, and enhanced SEO. React offers more flexibility and is ideal for highly dynamic single-page applications.

### Can I use React and Next.js together?**

- Yes, Next.js is built on top of React, so you can use React components within a Next.js application, leveraging the best of both worlds.

### Is learning Next.js difficult if I already know React?**

- Learning Next.js is relatively straightforward if you are already familiar with React. The main new concepts are server-side rendering and static site generation.

### What are the SEO benefits of Next.js?**

- Next.js improves SEO by enabling server-side rendering and static site generation, ensuring that search engines can easily crawl and index your pages. This leads to better search engine rankings and visibility.

### Which companies use React and Next.js?**

- Many large companies use both frameworks. For example, Facebook, Instagram, and Airbnb use React, while Next.js is used by Netflix, Twitch, Nike.

**Happy Coding!** 😊

]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/React vs Next.js Choosing the Right Framework for Your Next Project.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[7 Important JavaScript Concepts Every Developer Should Know]]></title>
            <link>https://nishangiri.dev/blog/seven-javascript-concepts</link>
            <guid>https://nishangiri.dev/blog/seven-javascript-concepts</guid>
            <pubDate>Sun, 16 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Discover essential JavaScript concepts every developer should master to enhance their coding skills and build robust applications. This comprehensive guide covers variables, functions, scope, closures, asynchronous JavaScript, prototypes, inheritance, ES6 features, and error handling. Each section includes clear explanations with practical examples. Learn how to leverage modern JavaScript features to streamline your development process and improve your understanding of this versatile language. Read more now!]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-06-16" />

<Image 
  src="/posts/Important Javascript Concepts.png" 
  alt="7 Important JavaScript Concepts " 
  width={1200} 
  height={600} 
/>

JavaScript is a powerful and versatile programming language that is essential for modern web development. Mastering its core concepts can significantly enhance your coding skills and open up numerous opportunities in the tech industry. In this post, we’ll explore seven crucial JavaScript concepts that every developer should know.

## Table of Contents
<TableOfContents items={[
  { text: 'Variables and Data Types', href: '#variables-and-data-types' },
  { text: 'Functions', href: '#functions' },
  { text: 'Scope and Closures', href: '#scope-and-closures' },
  { text: 'Asynchronous JavaScript', href: '#asynchronous-javascript' },
  { text: 'Prototypes and Inheritance', href: '#prototypes-and-inheritance' },
  { text: 'ES6+ Features', href: '#es6-features' },
  { text: 'Error Handling', href: '#error-handling' },
  { text: 'Conclusion', href: '#conclusion' }
]} />


## Variables and Data Types
Understanding variables and data types in JavaScript is crucial for writing effective and bug-free code. JavaScript offers three primary ways to declare variables: var, let, and const. Each has its own characteristics and best use cases, which we'll explore in detail below. Additionally, we'll dive into JavaScript's data types and common pitfalls to avoid.

### Var, Let, and Const

**1. Var**

- **Scope**: var is function-scoped, meaning it is only accessible within the function it is declared in. If declared outside a function, it becomes globally scoped.
- **Hoisting**: Variables declared with var are hoisted to the top of their scope, but their initialization is not. This means you can reference a var variable before its declaration, but it will return undefined until the declaration line is executed.
- **Redeclaration and Update**: Variables declared with var can be redeclared and updated within their scope.

**Example**:
```js
function exampleVar() {
  console.log(x); // undefined (hoisted)
  var x = 5;
  console.log(x); // 5
  var x = 10;
  console.log(x); // 10 (redeclared and updated)
}
exampleVar();
```

**2. Let**
- **Scope**: let is block-scoped, meaning it is only accessible within the block (i.e., within curly braces {}) it is declared in. This includes blocks like if statements, loops, etc.
- **Hoisting**: Variables declared with let are also hoisted, but not initialized. This leads to a "Temporal Dead Zone" (TDZ) from the start of the block until the declaration is encountered, where the variable cannot be accessed.
- **Redeclaration and Update**: let variables can be updated but not redeclared within the same scope.

**Example**:
```js
function exampleLet() {
  // console.log(y); // ReferenceError: Cannot access 'y' before initialization
  let y = 5;
  console.log(y); // 5
  y = 10;
  console.log(y); // 10 (updated)
  // let y = 20; // SyntaxError: Identifier 'y' has already been declared
}
exampleLet();
```

**3. Const**

- **Scope**: Like let, const is block-scoped.
- **Hoisting**: const variables are also hoisted but not initialized, leading to the same "Temporal Dead Zone" as let.
- **Redeclaration and Update**: const variables cannot be updated or redeclared. They must be initialized at the time of declaration.

**Example**:
```js
function exampleConst() {
  const z = 5;
  console.log(z); // 5
  // z = 10; // TypeError: Assignment to constant variable.
  // const z = 20; // SyntaxError: Identifier 'z' has already been declared
}
exampleConst();
```

### Data Types
JavaScript has several data types, divided into two categories: primitive and reference types.

**1. Primitive Types**

- **Number**: Represents both integer and floating-point numbers. Example: 42 or 3.14.
- **String**: Represents a sequence of characters. Example: "Hello, world!".
- **Boolean**: Represents logical entities and can have two values: true or false.
- **Null**: Represents the intentional absence of any object value. Example: null.
- **Undefined**: Indicates that a variable has been declared but has not yet been assigned a value. Example: undefined.
- **Symbol**: Represents a unique and immutable value, often used as keys for object properties.

**Example**:
```js
let num = 42;
let str = "Hello, world!";
let bool = true;
let empty = null;
let notAssigned;
let sym = Symbol('unique');
```

**2. Reference Types**

- **Object**: Collections of properties, where each property is a key-value pair. Objects can contain other objects, arrays, functions, etc. Example: `{ name: "John", age: 25 }.`
- **Array**: Ordered collections of data. Example: `[1, 2, 3, 4].`
- **Function**: Reusable blocks of code. Example: `function greet() { return "Hello!"; }.`

**Example**:
```js
let person = {
  name: "John",
  age: 25
};

let numbers = [1, 2, 3, 4];

function greet() {
  return "Hello!";
}
```

## Functions
Functions are the building blocks of JavaScript applications. They encapsulate code for reuse and modularity. Understanding the different types of functions and their use cases is essential for writing clean and efficient code. In this section, we'll explore various types of functions, their syntax, and their applications with detailed examples and outputs.

### Types of Functions
**1. Function Declarations** are one of the most common ways to define functions in JavaScript. They are hoisted to the top of their scope, meaning they can be used before they are defined in the code.

**Syntax**:
```js
function functionName(parameters) {
  // function body
}
```

**Example**:
```js
function greet() {
  return 'Hello!';
}
console.log(greet()); // Output: Hello!
```
In this example, the greet function is declared and then called. Due to hoisting, it can be called even if the function call appears before the function declaration in the code.

**2. Function Expressions** are functions defined as part of an expression. They are not hoisted, which means they cannot be used before their definition.

**Syntax**:
```js
const functionName = function(parameters) {
  // function body
};
```

**Example**:
```js
const greetExpression = function() {
  return 'Hello!';
};
console.log(greetExpression()); // Output: Hello!
```

**3. Arrow Functions**, introduced in ES6, provide a concise syntax and lexically bind the this value, making them ideal for non-method functions.

**Syntax**:
```js
const functionName = (parameters) => {
  // function body
};
```

**Example**:
```js
const greetArrow = () => 'Hello!';
console.log(greetArrow()); // Output: Hello!
```
Arrow functions offer a shorter syntax and are particularly useful in callbacks and functional programming patterns.

### Parameters and Arguments
Functions in JavaScript can accept parameters and arguments to make them more flexible and reusable.

**1. Default Parameters** allow you to initialize parameters with default values if no arguments are passed.

**Syntax**:
```js
function functionName(param1 = defaultValue) {
  // function body
}
```

**Example**:
```js
function greet(name = 'Guest') {
  return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, Guest!
console.log(greet('John')); // Output: Hello, John!
```
In this example, the greet function assigns 'Guest' as the default value for the name parameter if no argument is provided.

**2. Rest Parameters and Spread Operator** allow functions to accept an indefinite number of arguments as an array, while the spread operator expands an array into individual elements.

**Syntax**:
```js
function functionName(...restParam) {
  // function body
}
```

**Example**:
```js
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6

const arr = [1, 2, 3];
console.log(...arr); // Output: 1 2 3
```
The sum function uses rest parameters to sum any number of arguments. The spread operator is used to expand the array arr into individual elements.

## Scope and Closures
Scope and closures are fundamental concepts in JavaScript that are crucial for managing variable visibility and memory. Grasping these concepts is essential for writing clean, efficient, and bug-free code. In this section, we’ll explore the different types of scope, how closures work, and practical examples to solidify your understanding.

### Scope
Scope determines the accessibility of variables in different parts of your code. JavaScript has three types of scope: global, function, and block scope.

**1. Global Scope:**
Variables declared outside of any function or block are in the global scope. They can be accessed from anywhere in the code.

**Example**:
```js
let globalVar = 'I am global';

function testScope() {
  console.log(globalVar); // I am global
}

testScope();
console.log(globalVar); // I am global
```
In this example, globalVar is accessible both inside and outside the testScope function because it is globally scoped.

**2. Function Scope:**
Variables declared within a function are in the function scope. They can only be accessed within that function.

**Example**:
```js
function testScope() {
  let localVar = 'I am local';
  console.log(localVar); // I am local
}

testScope();
// console.log(localVar); // ReferenceError: localVar is not defined
```

Here, localVar is only accessible within the testScope function. Attempting to access it outside the function results in a reference error.

**3. Block Scope:**
Variables declared with let and const within a block (e.g., within curly braces {}) are in block scope. They are only accessible within that block.

**Example**:
```js
if (true) {
  let blockVar = 'I am block scoped';
  console.log(blockVar); // I am block scoped
}
// console.log(blockVar); // ReferenceError: blockVar is not defined
```
In this example, blockVar is only accessible within the if block. Trying to access it outside the block results in a reference error.

## Closures
Closures are a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables, even after the outer function has finished executing. Closures are used to create private variables and functions, encapsulate code, and maintain state.

**Example**:
```js
function makeCounter() {
  let count = 0;
  return function() {
    count++;
    return count;
  }
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
```
In this example, makeCounter returns a function that increments and returns the count variable. The returned function retains access to count even after makeCounter has finished executing, demonstrating a closure.

## Asynchronous JavaScript
Asynchronous JavaScript is a powerful feature that allows developers to write code that can perform long-running tasks without blocking the main thread. This is essential for creating responsive web applications. In this section, we'll explore the key concepts of asynchronous JavaScript, including callbacks, promises, and async/await, along with practical examples and their outputs.

### 1. Callbacks
Callbacks are functions passed as arguments to other functions and are executed after a specific task is completed. They were one of the first methods used to handle asynchronous operations in JavaScript.

**Example**:
```js
function fetchData(callback) {
  setTimeout(() => {
    callback('Data fetched');
  }, 1000);
}

fetchData(data => console.log(data));
```

**Output**:
```console
Data fetched
```

In this example, fetchData simulates an asynchronous operation using setTimeout, and the callback function logs the fetched data after the delay.

### 2. Promises
Promises provide a more robust and cleaner way to handle asynchronous operations compared to callbacks. A promise represents an operation that hasn't completed yet but is expected in the future. Promises have three states: pending, fulfilled, and rejected.

**Example**:
```js
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Data fetched');
  }, 1000);
});

promise.then(data => console.log(data));
```

**Output**:
```console
Data fetched
```

Here, the promise resolves with the fetched data after a delay. The .then method is used to handle the promise's fulfillment.

### 3. Chaining Promises
Promises can be chained to handle multiple asynchronous operations in a sequence.

**Example**:
```js
const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Data fetched');
  }, 1000);
});

fetchData
  .then(data => {
    console.log(data);
    return 'Processing data';
  })
  .then(process => {
    console.log(process);
  });
```

**Output**:
```console
Data fetched
Processing data
```
In this example, the first promise resolves with 'Data fetched', and the second .then method processes this data, demonstrating how promises can be chained.

### 4. Async/Await
Async/await, introduced in ES8, provides a more readable and synchronous-looking way to work with asynchronous code. async functions return a promise, and await is used to wait for the promise to resolve.

**Example**:
```js
async function fetchData() {
  const data = await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data fetched');
    }, 1000);
  });
  console.log(data);
}

fetchData();
```

**Output**:
```console
Data fetched
```
The fetchData function uses await to pause execution until the promise resolves, making the code more readable and easier to manage.

## Prototypes and Inheritance
Prototypes and inheritance are key concepts in JavaScript that allow objects to share properties and methods, enabling more efficient code reuse and design patterns. Here's a simplified explanation of these concepts.

### 1. Prototypes
In JavaScript, every object has a prototype. A prototype is also an object that provides a way to share properties and methods between objects. When you try to access a property or method on an object, JavaScript will look for it on the object itself first. If it doesn't find it, it will look at the object's prototype.

**Example**:
```js
function Person(name) {
  this.name = name;
}

Person.prototype.greet = function() {
  return `Hello, my name is ${this.name}`;
};

const john = new Person('John');
console.log(john.greet()); // Output: Hello, my name is John
```
In this example, greet is added to the Person prototype. Every instance of Person can access greet through the prototype.

### 2. Prototype Chain
The prototype chain is the mechanism by which JavaScript objects inherit properties and methods from other objects. If an object’s property is not found on the object itself, JavaScript continues searching up the prototype chain until it reaches the end (usually Object.prototype).

**Example**:
```js
console.log(john.toString()); // Output: [object Object]
```

Here, toString is not defined on john or Person.prototype, but it is found on Object.prototype, which is higher up the prototype chain.

### Inheritance
Inheritance allows one object to inherit properties and methods from another object. In JavaScript, inheritance is implemented through prototypes.

**Example**:
```js
function Employee(name, position) {
  Person.call(this, name); // Call the parent constructor
  this.position = position;
}

Employee.prototype = Object.create(Person.prototype); // Inherit from Person
Employee.prototype.constructor = Employee;

Employee.prototype.work = function() {
  return `${this.name} is working as a ${this.position}`;
};

const bob = new Employee('Bob', 'Engineer');
console.log(bob.greet()); // Output: Hello, my name is Bob
console.log(bob.work());  // Output: Bob is working as an Engineer
```
In this example, Employee inherits from Person, allowing Employee instances to use methods defined on Person.prototype, such as greet.

## ES6+ Features
ES6 (ECMAScript 2015) and subsequent versions introduced many features that have significantly improved JavaScript development. These features make the language more powerful, concise, and easier to work with. Here’s a simple explanation of some key ES6+ features.

### 1. Let and Const
let and const provide block-scoped variable declarations, replacing the function-scoped var.

**Example**:
```js
let x = 10;
const y = 20;

if (true) {
  let x = 30; // This x is block-scoped
  console.log(x); // Output: 30
}

console.log(x); // Output: 10
```

### 2. Arrow Functions
Arrow functions offer a concise syntax for writing functions and lexically bind the this value.

**Example**:
```js
const greet = (name) => `Hello, ${name}!`;
console.log(greet('John')); // Output: Hello, John!
```

### 3. Template Literals
Template literals provide an easier way to create strings, allowing embedded expressions.

**Example**:
```js
const name = 'John';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!
```

### 4. Destructuring
Destructuring allows you to unpack values from arrays or properties from objects into distinct variables.

**Example**:
```js
const [a, b] = [1, 2];
console.log(a); // Output: 1
console.log(b); // Output: 2

const {name, age} = {name: 'John', age: 25};
console.log(name); // Output: John
console.log(age); // Output: 25
```

### 5. Default Parameters
Default parameters allow you to set default values for function parameters.

**Example**:
```js
function greet(name = 'Guest') {
  return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, Guest!
console.log(greet('John')); // Output: Hello, John!
```

### 6. Spread and Rest Operators
The spread operator allows an iterable to expand in places where multiple arguments or elements are expected. The rest operator collects all remaining elements into an array.

**Example**:
```js
const arr = [1, 2, 3];
console.log(...arr); // Output: 1 2 3

function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
```

### 7. Classes
ES6 introduced a more intuitive and syntactically sugar way to create objects and deal with inheritance through the class keyword.

**Example**:
```js
class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    return `Hello, my name is ${this.name}`;
  }
}

const john = new Person('John');
console.log(john.greet()); // Output: Hello, my name is John
```

### 8. Promises
Promises provide a way to handle asynchronous operations more gracefully than callbacks.

**Example**:
```js
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Data fetched');
  }, 1000);
});

promise.then(data => console.log(data)); // Output: Data fetched
```

### 9. Modules
Modules allow you to split your code into separate files and functions, making it more manageable and reusable.

**Example**:
```js
// export.js
export const name = 'John';

// import.js
import { name } from './export.js';
console.log(name); // Output: John
```

### 10. Async/Await
Async/await provides a more readable and cleaner way to work with promises.

**Example**:
```js
async function fetchData() {
  const data = await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data fetched');
    }, 1000);
  });
  console.log(data);
}

fetchData(); // Output: Data fetched
```

## Error Handling
Error handling is an essential part of writing robust and reliable JavaScript code. It helps you manage unexpected situations and ensures your program can gracefully handle errors. Here's a simple explanation of error handling in JavaScript, including try/catch blocks and custom errors, with practical examples and their outputs.

### 1. Try/Catch
The try/catch statement allows you to handle errors gracefully by "trying" to execute a block of code and "catching" any errors that occur.

**Example**:
```js
try {
  throw new Error('Something went wrong');
} catch (error) {
  console.error(error.message);
}
```

**Output**:
```js
Something went wrong
```
In this example, the try block throws an error, which is then caught by the catch block. The error message is logged to the console.

### 2. Catching Specific Errors
You can catch specific errors and handle them differently based on their type or message.

**Example**:
```js
try {
  JSON.parse('Invalid JSON');
} catch (error) {
  if (error instanceof SyntaxError) {
    console.error('JSON Syntax Error:', error.message);
  } else {
    console.error('Unknown Error:', error.message);
  }
}
```

**Output**:
```js
JSON Syntax Error: Unexpected token I in JSON at position 0
```
Here, the catch block checks if the error is a SyntaxError and handles it accordingly. Other errors are handled in a generic manner.

### 3. Finally
The finally block is used to execute code after the try and catch blocks, regardless of whether an error was thrown or not.

**Example**:
```js
try {
  console.log('Trying...');
  throw new Error('Oops!');
} catch (error) {
  console.error('Caught:', error.message);
} finally {
  console.log('Finally block executed');
}
```

**Output**:
```js
Trying...
Caught: Oops!
Finally block executed
```

The finally block executes after the try and catch blocks, ensuring that cleanup or finalization code runs no matter what.

### 4. Custom Errors
You can create custom error types to provide more meaningful error messages and handle specific error conditions in your application.

**Example**:
```js
class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = 'CustomError';
  }
}

try {
  throw new CustomError('This is a custom error');
} catch (error) {
  console.error(error.name + ': ' + error.message);
}
```

**Output**:
```js
CustomError: This is a custom error
```
In this example, a custom error class CustomError is defined, and an instance of this error is thrown and caught, providing a specific error name and message.

## Conclusion
Mastering the fundamental concepts of JavaScript—variables and data types, functions, scope and closures, asynchronous programming, prototypes and inheritance, ES6+ features, and error-handling is crucial for any developer aiming to write efficient, maintainable, and robust code.

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/Important Javascript Concepts.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[How to Use Styled-Components in React]]></title>
            <link>https://nishangiri.dev/blog/styled-component-react</link>
            <guid>https://nishangiri.dev/blog/styled-component-react</guid>
            <pubDate>Thu, 13 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn how to use styled-components in React to create seamless and maintainable styles for your application. This guide covers the basics, setup, advanced features, and best practices.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-06-13" />

<Image 
  src="/posts/Styled Components in React.png" 
  alt="How to Use Styled-Components in React " 
  width={1200} 
  height={600} 
/>

Styling is important for any web app. It helps create a good user experience. With React, we have new ways to add styles. One popular way is using styled-components. This blog will show you how to use styled-components in React. We'll cover the basics, some advanced features, and best practices.

### Table of Contents

<TableOfContents items={[
  { text: 'What are Styled-Components?', href: '#what-are-styled-components' },
  { text: 'Benefits of Using Styled-Components', href: '#benefits-of-using-styled-components' },
  { text: 'Setting Up Styled-Components in a React Project', href: '#setting-up-styled-components-in-a-react-project' },
  { text: 'Basic Usage of Styled-Components', href: '#basic-usage-of-styled-components',
    subItems: [
      { text: 'Creating Styled Components', href: '#creating-styled-components' },
      { text: 'Props and Dynamic Styles', href: '#props-and-dynamic-styles' }
    ]
  },
  { text: 'Advanced Features', href: '#advanced-features',
    subItems: [
      { text: 'Theming', href: '#theming' },
      { text: 'Global Styles', href: '#global-styles' },
      { text: 'Extending Styles', href: '#extending-styles' },
      { text: 'Animations', href: '#animations' },
      { text: 'Polymorphic Components', href: '#polymorphic-components' }
    ]
  },
  { text: 'Best Practices for Using Styled-Components', href: '#best-practices-for-using-styled-components' },
  { text: 'Common Pitfalls and How to Avoid Them', href: '#common-pitfalls-and-how-to-avoid-them' },
  { text: 'Conclusion', href: '#conclusion' },
]} />


---

### What are Styled-Components?

<CustomLink text="Styled-components" link="https://styled-components.com/"/> is a library that helps you write CSS in your JavaScript files. It uses tagged template literals to style your components. This makes it easy to keep your styles scoped to specific components and adjust them based on props. This makes styling in React more modular and reusable.

### Benefits of Using Styled-Components

Styled-components offer many benefits:
- **Scoped Styles**: Styles only apply to the components you want, reducing conflicts.
- **Dynamic Styling**: Adjust styles based on props, making it easy to create responsive designs.
- **Improved Readability**: Styles are written with the components, making the code easier to understand.
- **Performance Optimization**: Optimizes rendering and re-rendering of styled components, improving app performance.

### Setting Up Styled-Components in a React Project

To get started with styled-components:

1. **Install styled-components**:
   ```bash
   npm install styled-components
   # or
   yarn add styled-components
   ```
2. **Create a new React app (if needed):**
    ```bash
    npx create-react-app styled-components-demo
    cd styled-components-demo
    ```
3. **Import styled-components into your project:**
    ```js
    import styled from 'styled-components';
    ```

## Basic Usage of Styled-Components
### Creating Styled Components

Here’s an example of a styled button component:
```js
const Button = styled.button`
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;

  &:hover {
    background-color: #0056b3;
  }
`;
```

Use this component like any other React component:
```js
import React from 'react';

function App() {
  return (
    <div>
      <h1>Welcome to Styled-Components!</h1>
      <Button>Click me</Button>
    </div>
  );
}

export default App;
```

### Props and Dynamic Styles

You can pass props to dynamically adjust styles:
```js
const Button = styled.button`
  background-color: ${props => props.primary ? '#007bff' : 'white'};
  color: ${props => props.primary ? 'white' : 'black'};
  border: ${props => props.primary ? 'none' : '2px solid #007bff'};
`;

function App() {
  return (
    <div>
      <Button primary>Primary Button</Button>
      <Button>Secondary Button</Button>
    </div>
  );
}
```

## Advanced Features
### Theming

Styled-components make it easy to apply themes:
```js
const theme = {
  primaryColor: '#007bff',
  secondaryColor: '#6c757d',
};

const Button = styled.button`
  background-color: ${props => props.primary ? props.theme.primaryColor : props.theme.secondaryColor};
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
`;

import { ThemeProvider } from 'styled-components';

function App() {
  return (
    <ThemeProvider theme={theme}>
      <Button primary>Primary Button</Button>
      <Button>Secondary Button</Button>
    </ThemeProvider>
  );
}
```

### Global Styles

Define global styles using createGlobalStyle:
```js
import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  body {
    font-family: 'Arial', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
`;

function App() {
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <Button primary>Primary Button</Button>
      <Button>Secondary Button</Button>
    </ThemeProvider>
  );
}
```

### Extending Styles

Extend existing styles easily:
```js
const Button = styled.button`
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
`;

const PrimaryButton = styled(Button)`
  background-color: #0056b3;
`;
```

### Animations

Create and use animations with styled-components:
```js
import styled, { keyframes } from 'styled-components';

const slideIn = keyframes`
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
`;

const Toast = styled.div`
  animation: ${slideIn} 0.5s ease-in-out;
  border-radius: 5px;
  padding: 20px;
  position: fixed;
  top: 20px;
  right: 20px;
  background-color: #007bff;
  color: white;
`;

function App() {
  return <Toast>Slide in animation!</Toast>;
}
```

### Polymorphic Components

The "as" prop changes the rendered HTML element:
```js
const StyledContainer = styled.section`
  max-width: 1024px;
  margin: 0 auto;
`;

function App() {
  return (
    <StyledContainer as="div">
      <h1>Rendered as a div</h1>
    </StyledContainer>
  );
}
```
## Best Practices for Using Styled-Components

- **Organize your styles**: Keep your styled components in a separate file or folder to maintain a clean structure.
- **Naming conventions**: Use meaningful names for your styled components to make your code easier to read.
- **Reusability**: Create reusable components and themes to maintain consistency across your application.
- **Avoid excessive nesting**: Limit the depth of nesting in your styles to keep them maintainable and fast.

## Common Pitfalls and How to Avoid Them

- **Learning curve**: Styled-components may have a steep learning curve for new developers. Start with basic examples and gradually explore advanced features.
- **Performance concerns**: While styled-components are optimized, excessive use of dynamic styles can impact performance. Use static styles where possible.
- **Lock-in**: Styled-components are tied to React and JavaScript, making it harder to switch frameworks. Evaluate if it suits your long-term project needs.

## Conclusion

Styled-components offer a powerful and flexible way to style React components. With scoped and dynamic styles, theming support, and advanced features like animations and polymorphic components, styled-components enhance the development experience and improve code maintainability. Whether you're building a simple website or a complex application, styled-components can streamline your styling process.

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/Styled Components in React.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Styling React Applications in 2024: Tailwind CSS, Radix, and ShadCN UI]]></title>
            <link>https://nishangiri.dev/blog/styling-react-apps</link>
            <guid>https://nishangiri.dev/blog/styling-react-apps</guid>
            <pubDate>Tue, 04 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Discover how to style React applications in 2024 using Tailwind CSS, Radix, and ShadCN UI. Learn the latest trends and best practices for creating modern, responsive, and accessible UIs with these powerful tools.]]></description>
            <content:encoded><![CDATA[
<AuthorInfo date="2024-06-04" />

<Image
  src="/posts/Styling React Applications Tailwind CSS, Radix, and ShadCN UI.png"
  alt="Styling React Applications Tailwind CSS, Radix, and ShadCN UI"
  width={1200}
  height={600}
/>

In 2024, making your React apps look good is easier than ever. Developers have lots of tools to help create attractive and responsive interfaces. Three of the best tools right now are Tailwind CSS, Radix UI, and ShadCN UI. This blog will show you how to use these tools to improve your React applications. Whether you're an experienced developer or just starting, you'll find useful tips and examples here.

Tailwind CSS, Radix UI, and ShadCN UI each bring something unique to the table. Tailwind CSS is great for its utility-first styling. Radix UI offers accessible, unstyled components. ShadCN UI combines the best of both with a modern library built on Radix and styled with Tailwind. Let's dive in!

## Table of Contents

<TableOfContents
  items={[
    {
      text: "Tailwind CSS",
      href: "#tailwind-css",
      subItems: [
        { text: "Overview", href: "#overview" },
        { text: "Advantages", href: "#advantages" },
        { text: "Installation and Setup", href: "#installation-and-setup" },
        { text: "Usage and Examples", href: "#usage-and-examples" },
        { text: "Best Practices", href: "#best-practices" },
      ],
    },
    {
      text: "Radix UI",
      href: "#radix-ui",
      subItems: [
        { text: "Overview", href: "#overview-1" },
        { text: "Key Features", href: "#key-features" },
        { text: "Integration with React", href: "#integration-with-react" },
        { text: "Example Components", href: "#example-components" },
        { text: "Tips for Use", href: "#tips-for-use" },
      ],
    },
    {
      text: "ShadCN UI",
      href: "#shadcn-ui",
      subItems: [
        { text: "Introduction", href: "#introduction-1" },
        { text: "Features and Benefits", href: "#features-and-benefits" },
        { text: "Setup and Configuration", href: "#setup-and-configuration" },
        { text: "Example Usage", href: "#example-usage" },
        { text: "Best Practices", href: "#best-practices-1" },
      ],
    },
    { text: "Comparison and Use Cases", href: "#comparison-and-use-cases" },
    { text: "Combining These Tools", href: "#combining-these-tools" },
    { text: "Conclusion", href: "#conclusion" },
    { text: "FAQs", href: "#faqs" },
  ]}
/>

### Tailwind CSS

#### Overview

<CustomLink text="Tailwind CSS" link="https://tailwindcss.com/" /> is a utility-first CSS framework. This means you use small, reusable classes to style your elements directly in your HTML. It's known for being efficient and flexible.

#### Advantages

- **Efficiency**: Reduces the need for writing custom CSS.
- **Flexibility**: Allows for extensive customization while maintaining a consistent design language.
- **Responsive Design**: Built-in classes for creating responsive layouts easily.

#### Installation and Setup

To add Tailwind CSS to your React project, run these commands:

```bash
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
```

Then, add these lines to your CSS file:

```css
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
```

### Usage and Examples

Use Tailwind classes directly in your JSX:

```jsx
<div className="bg-blue-500 text-white p-4 rounded-lg">
  Hello, Tailwind!
</div>
```

### Best Practices

- **Stick to Utility Classes**: Use Tailwind's classes as much as you can.
- **Customize When Needed**: Adjust Tailwind settings in the `tailwind.config.js` file.
- **Think Mobile First**: Use Tailwind's responsive classes to make your design mobile-friendly.

### Radix UI

#### Overview

<CustomLink text="Radix UI" link="https://www.radix-ui.com/" /> provides unstyled, accessible components for React apps. You can style them any way you like.

#### Key Features

- **Accessibility**: Components meet accessibility standards.
- **Flexibility**: Style components however you want.
- **Incremental Adoption**: Use only the components you need.

#### Integration with React

Install Radix UI components with npm:

```bash
npm install @radix-ui/react-toast @radix-ui/react-accordion
```

### Import and use them in your project:

```jsx
import { Toast } from '@radix-ui/react-toast';
```

### Example Components

```jsx
import * as Toggle from '@radix-ui/react-toggle';

function App() {
  return (
    <Toggle.Root className="bg-indigo-600 text-white font-semibold px-10">
      Click Me
    </Toggle.Root>
  );
}
```

#### Tips for Use

- **Combine with Tailwind**: Style Radix components using Tailwind classes.
- **Server-Side Rendering**: Radix works well with SSR frameworks like Next.js.

### ShadCN UI

#### Introduction

<CustomLink text="ShadCN UI" link="https://ui.shadcn.com/is" />a modern component library built on Radix UI and styled with Tailwind CSS. It offers a wide range of ready-to-use components.

#### Features and Benefits

- **Lots of Components**: Provides many pre-built components.
- **Tailwind Integration**: Works seamlessly with Tailwind CSS.
- **TypeScript Support**: Works well with TypeScript.

#### Setup and Configuration

Install ShadCN UI using npm:

```bash
npx shadcn-ui@latest init
```

Follow the prompts to configure your project.

### Example Usage

```jsx
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";

function App() {
  return (
    <HoverCard>
      <HoverCardTrigger className="rounded-xl text-white py-2 px-4 bg-slate-500">
        First ShadCN Component
      </HoverCardTrigger>
      <HoverCardContent className="font-bold text-slate-500 w-max">
        My first of many components
      </HoverCardContent>
    </HoverCard>
  );
}
```

#### Best Practices

- **Keep Styles Consistent**: Use Tailwind classes for uniform styling.
- **Customize Components**: Adjust components as needed using Tailwind.

### Comparison and Use Cases

#### Tailwind CSS

- **Best For**: Quick, utility-first styling and responsive designs.
- **Pros**: Efficiency, flexibility, responsive design.
- **Cons**: Can become cluttered with too many classes.

#### Radix UI

- **Best For**: Accessible, unstyled components you can customize.
- **Pros**: Accessibility, flexibility, incremental adoption.
- **Cons**: Requires additional styling work.

#### ShadCN UI

- **Best For**: A modern, comprehensive UI library built on Radix with Tailwind styling.
- **Pros**: Comprehensive components, seamless Tailwind integration, TypeScript support.
- **Cons**: Learning curve if unfamiliar with Radix or Tailwind.

### Combining These Tools

To combine Tailwind CSS, Radix UI, and ShadCN UI:

1. **Setup**: Install and configure each tool.
2. **Component Integration**: Use Radix components and style them with Tailwind. Add ShadCN UI components as needed.
3. **Consistent Styling**: Use Tailwind's classes for all components to maintain a uniform design.

### Conclusion

Using Tailwind CSS, Radix UI, and ShadCN UI together can greatly improve your React applications in 2024. Each tool offers unique benefits, and combining them can help you create efficient, accessible, and visually appealing applications.

### FAQs

**Q1: Can I use Tailwind CSS with any React component library?**  
Yes, Tailwind CSS works with most React component libraries, including Radix UI and ShadCN UI.

**Q2: Is Radix UI suitable for large-scale applications?**  
Absolutely. Radix UI's focus on accessibility and flexibility makes it great for both small and large projects.

**Q3: How does ShadCN UI differ from other UI libraries?**  
ShadCN UI combines Radix UI's flexibility with Tailwind CSS's styling power, offering a modern solution for React applications.

For more information on these tools, check out resources from [LogRocket](https://blog.logrocket.com/radix-ui-adoption-guide/), [freeCodeCamp](https://www.freecodecamp.org/news/react-libraries-to-use-in-2024/), and [SitePoint](https://www.sitepoint.com/enhance-your-react-apps-with-shadcn-utilities-and-components/).

By following these tips and utilizing these tools, you can ensure your React applications are stylish, accessible, and efficient, setting you up for success in 2024 and beyond.

**Happy Coding!** 😊]]></content:encoded>
            <enclosure url="https://nishangiri.dev/posts/Styling React Applications Tailwind CSS, Radix, and ShadCN UI.png" length="0" type="image/png"/>
        </item>
    </channel>
</rss>