Ars Dev
1.98K subscribers
70 photos
7 videos
75 links
Hi, I’m Ars! Here I share practical insights on programming and AI πŸš€

To learn more JOIN my private community https://www.skool.com/ars-dev-hub-3159/about?ref=71f574f3ce3542eb976d068c3e133e1b

Contact: @ars_kylnyk
Download Telegram
Implementing Dark Mode Support πŸŒ™

Dark mode is no longer just a trendβ€”it’s an essential feature for accessibility and user comfort. Modern apps are expected to adapt to system preferences seamlessly.

πŸ›  Easy Implementation with React Native

Thanks to React Native’s useColorScheme(), your app can automatically switch themes:

import { NavigationContainer, DefaultTheme, DarkTheme } from '@react-navigation/native';
import { useColorScheme } from 'react-native';

function App() {
const scheme = useColorScheme();

return (
<NavigationContainer theme={scheme === 'dark' ? DarkTheme : DefaultTheme}>
{/* Your app content */}
</NavigationContainer>
);
}



For manual theme toggling, use the Appearance API:

import { Appearance } from 'react-native';

// Toggle theme manually
Appearance.setColorScheme('dark');


React Native Hub
⚑ Optimize Performance with `useCallback`

Using hooks incorrectly can lead to performance issues and memory leaks. One common mistake is redefining functions inside components, which causes unnecessary re-renders.

❌ Incorrect Usage

πŸ”΄ Functin recreated on every render, causing performance issues:


const renderItem = ({ item }) => (
<ItemComponent data={item} onPress={() => handlePress(item.id)} />
);



βœ… Optimized Usage with `useCallback`

βœ… Memoizes function references to prevent unnecessary re-renders:


const renderItem = useCallback(({ item }) => (
<ItemComponent data={item} onPress={handlePress} />
), [handlePress]);

const handlePress = useCallback((id) => {
// operations
}, []);



Using useCallback ensures that renderItem remains the same across renders, significantly improving list performance in React Native apps. πŸš€

React Native Hub
🎨 Explore the Latest in Mobile UI Design! πŸ“±

Looking for fresh inspiration to elevate your app's user interface? Check out the latest compilation of flat and professional mobile app designs that emphasize clarity and functionality. These sleek designs showcase how minimalism and vibrant colors can create dynamic and user-friendly interfaces.

Highlights:

Minimalist Aesthetics: Clean lines and simple shapes that prioritize content.

Vibrant Color Palettes: Use of bold colors to enhance visual appeal without overwhelming the user.

User-Centric Layouts: Designs that focus on intuitive navigation and accessibility.

Staying updated with current design trends is crucial for creating engaging and effective user experiences. These examples provide valuable insights into how to implement flat design principles effectively in your projects.

Dive into the full collection here: Mobile UI Design Examples: Flat & Professional β€” vol. 219

Elevate your app's design by embracing these modern UI trends! πŸš€

React Native Hub
Handle Asynchronous Code

πŸ”΄ The Problem:

Many developers neglect proper error handling in asynchronous operations like API calls. This can lead to unhandled promise rejections, app freezes, and unpredictable behavior.

πŸ”Ή Best Practice: Always use try/catch blocks to gracefully handle errors in async functions.

βœ… Correct Approach:


const fetchData = async (): Promise<void> => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Failed to fetch data:', error);
// Show an error message to the user
}
};


❌ Don’t Forget:

Ignoring errors can cause crashes in production.

Always log and handle errors gracefully to improve user experience.

πŸ’‘ Want to learn more about best practices in React Native? Follow the channel for expert tips! πŸš€

React Native Hub
Avoid Overusing Inline Styles in React Native

Using inline styles might seem convenient, but overusing them can hurt performance in large applications.

⚠️ The Problem:

❌ Inline styles are re-evaluated on every render, leading to:

- Unnecessary recalculations
- Slower rendering
- Poor performance in large lists & complex components

βœ… The Solution: Use `StyleSheet.create()`

Defining styles separately improves efficiency:


import { StyleSheet, Text, View } from 'react-native';

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 10,
},
text: {
fontSize: 18,
color: '#333',
},
});

const MyComponent = () => (
<View style={styles.container}>
<Text style={styles.text}>Optimized Styling</Text>
</View>
);



πŸ“Œ Key Takeaways:

βœ… Avoid inline styles in every component

βœ… Use `StyleSheet.create()` for better performance

βœ… Keep styles reusable & maintainable

⚑ Write cleaner, faster, and more efficient React Native code! πŸš€

React Native Hub
Why you should use React Native in 2025

React Native continues to dominate cross-platform mobile development, offering speed, efficiency, and cost savings. Here’s why it remains a top choice:

βœ… Faster Development & Cost Efficiency
Code once, run on both iOS & Androidβ€”saving time and budget. Hot Reloading boosts productivity.

⚑ Better Performance
With Fabric & TurboModules, apps are now 5x faster, rivaling native experiences.

🌎 Huge Ecosystem & Community Support
React Native thrives with active contributions & robust libraries for every need.

πŸ’‘ Used by Tech Giants
Meta, Airbnb, Shopify, Teslaβ€”trusted by the best for scalable apps.

🎯 Future-Proof Technology
Built on JavaScript & TypeScript, ensuring long-term support and easy integration.

πŸ“– Read more: Why React Native in 2025

React Native Hub
πŸ” Building Reusable Components: Best Practices

Creating reusable components is key to building scalable React Native apps. A well-structured component library ensures consistency and efficiency. Here’s how to do it right:

βœ… Props-Driven Design: Pass styles, text, and actions via props instead of hardcoding.

βœ… Use TypeScript: Define prop types for better maintainability and fewer runtime errors.

βœ… Optimize Performance: Use React.memo to prevent unnecessary re-renders.

βœ… Write Tests: Validate components using Jest & React Native Testing Library.

βœ… Document Components: Tools like Storybook help visualize and test UI elements.

Building reusable components saves time and keeps your app organized. What best practices do you use? Leave them below! ⬇️ πŸš€

React Native Hub
πŸš€ Optimize Functional Components with React.memo

Unnecessary re-renders can slow down your React Native app. React.memo helps optimize performance by memoizing functional components and reusing the last rendered output if props haven't changed.

πŸ”Ή How It Works:

- Skips re-renders when props remain the same.
- Reduces performance overhead in frequently rendered components.

πŸ”Ή Example Usage:


import React, { memo } from 'react';

const Element = ({ value, setValue }) => {
return (
<TouchableOpacity onPress={() => setValue(value * 2)}>
<Text>{value}</Text>
</TouchableOpacity>
);
};

export default memo(Element);



βœ… Use React.memo when:

- Components are rendered frequently.
- Props remain unchanged across renders.

⚠️ Avoid Overuse: Memoization adds overhead if applied unnecessarily. Use it wisely! πŸš€


React Native Hub
Minimize the Use of Inline Functions

Defining functions inside JSX might seem convenient, but it can hurt performance by creating new function instances on every render.

❌ Bad Practice:

Each re-render creates a new function, causing unnecessary child component updates.


<Button onPress={() => handlePress(item.id)} />


βœ… Better Approach:

Use useCallback to memoize functions and prevent unnecessary re-creation.


const handlePress = useCallback((id) => {
// handle press logic
}, []);

<Button onPress={handlePress} />


πŸ”₯ Why It Matters?

βœ”οΈ Reduces re-renders βœ…
βœ”οΈ Improves performance πŸš€
βœ”οΈ Keeps code clean & maintainable πŸ’‘

React Native Hub
The useEffect clean-up callback executes on every render

Most people think it executes only when the component unmounts, but that’s not true.

On every render, the clean-up callback from the previous render executes just before the next effect execution.

Let’s see an example:


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

useEffect(() => {
console.log('The current count is ', count)
return () => {
console.log('The previous count is ', count)
}
})

return <button onClick={() => setCount(count + 1)}>Click me</button>
}


This logs the following:


// Component mounts
The current count is 0

// Click
The previous count is 0
The current count is 1

// Click
The previous count is 1
The current count is 2

// Component unmounts
The previous count is 2


πŸš€ Why This Matters?

This behavior is essential for managing subscriptions, event listeners, and cleanup logic effectively.

Adding a dependency array ensures the effect runs only when needed.

React Native Hub
πŸ‘1
useEffect is a low-level utility that should be used only in library-like code

It’s common for junior React developers to use useEffect when they don’t need to. This can make code more complex, create flickers, or subtle bugs.

The most common case is to synchronize different useStates, where you actually need one single useState:


functionMyComponent() {
const [text, setText] =useState("Lorem ipsum dolor sit amet")

// You don't need to do this !!!
const [trimmedText, setTrimmedText] =useState("Lorem ip...")

useEffect(() => {
setTrimmedText(text.slice(0,8) +'...')
}, [text])
}

functionMyBetterComponent() {
const [text, setText] =useState("Lorem ipsum dolor sit amet")

// Do this instead:
// (each time text changes, the component will re-render so trimmedText
// will be up-to-date)
const trimmedText = text.slice(0,8) +'...'
}



React Native Hub
πŸ‘1
Use the key prop to reset internal state

When the key prop changes on an element, the render of this element is not interpreted as an update, but as an unmount plus a mount of a brand new component instance with a fresh state.

function Layout({ currentItem }) {
/* When currentItem changes, we want any useState inside <EditForm/>
to be reset to a new initial value corresponding to the new item */
return (
<EditForm
item={currentItem}
key={currentItem.id}
/>
)
}


React Native Hub
πŸ‘1
πŸ”’ Implementing Expo Biometric Authentication

Biometric authentication (Face ID, Touch ID, fingerprint) enhances security and improves the user experience in mobile apps. With Expo’s LocalAuthentication API, integrating it into your React Native app is seamless. Here’s how you can do it! πŸš€

1️⃣ Install the LocalAuthentication API

First, install the required package:


npx expo install expo-local-authentication


2️⃣ Check for Biometric Support

Before prompting authentication, check if the device supports biometrics:


import * as LocalAuthentication from 'expo-local-authentication';

const checkBiometricSupport = async () => {
const isHardwareAvailable = await LocalAuthentication.hasHardwareAsync();
const supportedTypes = await LocalAuthentication.supportedAuthenticationTypesAsync();

console.log('Biometric Supported:', isHardwareAvailable);
console.log('Supported Types:', supportedTypes);
};


3️⃣ Prompt for Authentication

Trigger authentication when the user tries to access a protected section:


const authenticateUser = async () => {
const result = await LocalAuthentication.authenticateAsync({
promptMessage: 'Authenticate to continue',
fallbackLabel: 'Enter passcode',
});

if (result.success) {
console.log('Authentication Successful!');
} else {
console.log('Authentication Failed:', result.error);
}
};


4️⃣ Implement in a Component

Here’s how you can put it all together in a button:


import React from 'react';
import { View, Button, Alert } from 'react-native';
import * as LocalAuthentication from 'expo-local-authentication';

const BiometricAuth = () => {
const handleAuth = async () => {
const result = await LocalAuthentication.authenticateAsync({
promptMessage: 'Authenticate with Biometrics',
});

Alert.alert(result.success ? 'Authenticated' : 'Failed', result.success ? 'Access Granted' : 'Access Denied');
};

return (
<View>
<Button title="Login with Biometrics" onPress={handleAuth} />
</View>
);
};

export default BiometricAuth;


React Native Hub
πŸ‘3⚑1πŸ”₯1
🎨 Best Practices for Styling Mobile Apps

Styling plays a crucial role in building beautiful and maintainable React Native apps. Following best practices ensures consistency, better performance, and easier scalability. Here are some key takeaways:

βœ… Use StyleSheet.create() – This optimizes performance by preventing unnecessary re-renders.

βœ… Leverage Global Styles – Define common styles in a separate file to maintain consistency across the app.

βœ… Use Theme-Based Styling – Implement dark mode and dynamic themes using context or state management.

βœ… Avoid Inline Styles – Overusing inline styles leads to performance issues and redundant recalculations.

βœ… Use Flexbox for Layouts – Flexbox provides a responsive and adaptive layout system.

βœ… Styled Components – Reusable components for common UI elements.

By following these best practices, you can create visually appealing, efficient, and scalable React Native applications.

πŸ“– Read more: Full Article Here

React Native Hub
🎯 Discriminated Unions: Managing Complex State in React Native

Handling complex state can lead to unexpected bugs if not structured properly. Discriminated unions provide a powerful way to manage state transitions explicitly, ensuring type safety and preventing invalid states.

πŸ”Ή What Are Discriminated Unions?

A discriminated union is a TypeScript feature that allows defining multiple state variations with a common β€œdiscriminator” property.

πŸ“Œ Example: Managing Fetch States


type FetchState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: string[] }
| { status: 'error'; error: string };

const fetchReducer = (state: FetchState, action: any): FetchState => {
switch (action.type) {
case 'FETCH_START':
return { status: 'loading' };
case 'FETCH_SUCCESS':
return { status: 'success', data: action.payload };
case 'FETCH_ERROR':
return { status: 'error', error: action.payload };
default:
return state;
}
};



βœ… Why Use Discriminated Unions?

- Ensures state transitions are explicit and well-defined

- Prevents invalid states (e.g., having both data and `error`)

- Improves type safety and reduces runtime errors

By structuring your state this way, your application logic remains predictable and easier to maintain! πŸš€

React Native Hub
πŸ”Ή Generics in React: Reusable & Flexible Components πŸš€

Generics in TypeScript allow you to build reusable and strongly-typed components that adapt to different data structures. This is especially useful for handling lists, forms, or APIs where the structure varies.

πŸ“Œ Example: A Reusable Table Component


type TableProps<T> = {
data: T[];
renderRow: (item: T) => React.ReactNode;
};

function Table<T>({ data, renderRow }: TableProps<T>) {
return (
<table>
<tbody>{data.map((item, index) => <tr key={index}>{renderRow(item)}</tr>)}</tbody>
</table>
);
}

// Usage
type User = { id: number; name: string };
const users: User[] = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];

<Tabledata={users}
renderRow={(user) => (
<>
<td>{user.id}</td>
<td>{user.name}</td>
</>
)}
/>;



πŸ”₯ Why Use Generics?

βœ… Type-Safe: Enforces correct data structures at compile-time

βœ… Reusable: Works with any data type, reducing duplicate code

βœ… Flexible: Keeps your components dynamic without sacrificing type safety

By leveraging generics, you can build components that adapt to various use cases while maintaining clean and maintainable code! πŸ’‘

React Native Hub
πŸ‘2
What Is Cursor AI?

Cursor AI is an intelligent code editor built on Visual Studio Code, enhanced with robust AI capabilities. It offers features like:

βœ… Autocompletion: Context-aware code suggestions.

βœ… Code Generation: Write components, functions, or tests with natural language prompts.

βœ… Debugging Assistance: Identify errors and receive fixes in real time.

βœ… Documentation Search: Instant access to React Native APIs and libraries.

For React Native developers, this means faster iteration, reduced boilerplate code, and fewer context switches between tools.

https://www.cursor.com/

React Native Hub
πŸ‘3
Mapped Types: Transforming Props and State

Mapped types in TypeScript allow you to create new types by transforming existing ones. This is particularly useful for defining derived states, props, or configurations in React Native applications.

πŸ”Ή Example: Partial Form Props

Let's say you have a form with fields like nameemail, and age. You can use mapped types to define an error object that corresponds to each field dynamically:


type FormValues = {
name: string;
email: string;
age: number;
};

// Mapped Type for Errors
type FormErrors<T> = {
[K in keyof T]?: string;
};

const errors: FormErrors<FormValues> = {
name: "Name is required",
email: "Email is invalid",
};



βœ… Why It’s Useful:

πŸ”Ή Flexible Form Handling β€“ Easily create types for form validation without duplicating fields.

πŸ”Ή Ensures Type Safety β€“ Prevents typos and ensures every field has a corresponding error type.

πŸ”Ή Reusable & Scalable β€“ Can be applied to API responses, configurations, and component props.

React Native Hub
My First Medium Article is Live! πŸš€

Hey everyone! I just published my first article on Medium about.

πŸ‘‰ Read it here: https://medium.com/@arsdev/how-i-increased-list-scroll-fps-from-30-to-58-in-react-native-34504f8d802c

If you find it useful, I’d really appreciate your claps, comments, and sharesβ€”they help a lot!πŸ’™

Thanks for your support! πŸ™Œ

React Native Hub
Please open Telegram to view this post
VIEW IN TELEGRAM
πŸ‘4
From Solo to Duo: Transitioning to Pair Programming πŸ‘₯

Working alone has its perks, but have you ever considered the power of pair programming? This article explores how switching from solo development to coding with a partner can boost productivity, improve code quality, and accelerate learning.

πŸš€ Read article here

Have you tried pair programming? Share your thoughts in the comments! πŸ’¬

React Native Hub