Ars Dev
رفتن به کانال در Telegram
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
نمایش بیشترکشور مشخص نشده استفناوری و برنامهها32 872
1 862
مشترکین
اطلاعاتی وجود ندارد24 ساعت
-107 روز
-4730 روز
آرشیو پست ها
1 862
Open/Closed Principle (OCP)
✅ Definition: Software entities should be open for extension but closed for modification.
✅ In React: Use higher-order components (HOCs), render props, or composition to extend component behaviour without modifying the existing code.
Not following OCP: In this example, the
Button component has different styles based on the type prop. Every time a new button style is needed, we have to modify the existing Button component.
// ❌ BAD EXAMPLE - Violating OCP
import React from 'react';
const Button = ({ type, label }) => {
let style = {};
if (type === 'primary') {
style = { backgroundColor: 'blue', color: 'white' };
} else if (type === 'secondary') {
style = { backgroundColor: 'gray', color: 'white' };
} else if (type === 'danger') {
style = { backgroundColor: 'red', color: 'white' };
}
return <button style={style}>{label}</button>;
};
export default Button;
Every time we want to add a new button type, we need to modify the existing component by adding a new if or else if conditions, which violates OCP.
Following OCP: Instead of modifying the Button component for every new style, we can create a Higher-Order Component (HOC) that adds different styles based on the button type. This way, the Button component remains unchanged, and we can extend its behaviour by wrapping it with different HOCs.
// ✅ GOOD EXAMPLE - Following OCP
import React from 'react';
// Base Button Component
const Button = ({ style, label }) => {
return <button style={style}>{label}</button>;
};
// HOC for Primary Button
const withPrimaryStyle = (WrappedComponent) => {
return (props) => {
const style = { backgroundColor: 'blue', color: 'white' };
return <WrappedComponent {...props} style={style} />;
};
};
// HOC for Secondary Button
const withSecondaryStyle = (WrappedComponent) => {
return (props) => {
const style = { backgroundColor: 'gray', color: 'white' };
return <WrappedComponent {...props} style={style} />;
};
};
// HOC for Danger Button
const withDangerStyle = (WrappedComponent) => {
return (props) => {
const style = { backgroundColor: 'red', color: 'white' };
return <WrappedComponent {...props} style={style} />;
};
};
// Use the HOCs
const PrimaryButton = withPrimaryStyle(Button);
const SecondaryButton = withSecondaryStyle(Button);
const DangerButton = withDangerStyle(Button);
const App = () => (
<div>
<PrimaryButton label="Primary Button" />
<SecondaryButton label="Secondary Button" />
<DangerButton label="Danger Button" />
</div>
);
export default App;
React Native Hub1 862
Single Responsibility Principle (SRP)
✅ Definition: A component should have only one reason to change, meaning it should do one thing and do it well.
✅ In React: Break down large components into smaller, reusable pieces, each handling a single responsibility.
Not following SRP: In this example, the
UserProfile component handles fetching data, managing state, and rendering the UI—all in one component.
// ❌ BAD EXAMPLE - Violating SRP
import React, { useState, useEffect } from 'react';
const UserProfile = () => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchUserData = async () => {
try {
const response = await fetch('https://api.example.com/user');
const data = await response.json();
setUser(data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchUserData();
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
};
export default UserProfile;
Following SRP: Now, let’s refactor the code to adhere to the Single Responsibility Principle by breaking it into three separate components.
1. Custom Hook for Data Fetching (`useUserData`)
// ✅ GOOD EXAMPLE - Following SRP
import { useState, useEffect } from 'react';
const useUserData = () => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchUserData = async () => {
try {
const response = await fetch('https://api.example.com/user');
const data = await response.json();
setUser(data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchUserData();
}, []);
return { user, loading, error };
};
export default useUserData;
2. Loading and Error Handling Component (`UserInfo`)
// ✅ GOOD EXAMPLE - Following SRP
import React from 'react';
const UserInfo = ({ user, loading, error }) => {
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
};
export default UserInfo;
3. Main Component (`UserProfile`)
// ✅ GOOD EXAMPLE - Following SRP
import React from 'react';
import useUserData from './useUserData';
import UserInfo from './UserInfo';
const UserProfile = () => {
const { user, loading, error } = useUserData();
return <UserInfo user={user} loading={loading} error={error} />;
};
export default UserProfile;1 862
Mobile Bridge: Making WebViews Feel Native
Shopify's engineering team shares how they’ve enhanced the WebView experience using Mobile Bridge
🔍 What’s Inside:
- How Shopify allows WebViews to access native features (like camera, auth, navigation)
- Ensuring seamless communication between JavaScript and native platforms
- Techniques to make hybrid apps feel fully native to users
1 862
🚀 Master `useRef` for Better TextInput Handling in React Native
Struggling with managing input fields efficiently? Instead of relying on state updates that cause unnecessary re-renders,
useRef lets you interact directly with TextInput methods.
Why Use `useRef` with TextInput?
✅ Avoid Unnecessary Re-renders – Since useRef doesn’t trigger component updates, it’s great for performance.
✅ Easily Manage Focus – You can programmatically focus on an input field when needed.
✅ Access Input Methods Directly – Clear, blur, or manipulate text fields without updating state
Example Usage:
import React, { useRef, useState } from "react";
import { TextInput, Button, View } from "react-native";
const InputExample = () => {
const inputRef = useRef<TextInput>(null);
const focusInput = () => {
inputRef.current?.focus();
};
const clearInput = () => {
setValue("");
inputRef.current?.clear();
};
const handleSubmit = () => {
const inputValue = inputRef.current?.value || ''; // Get the current value
console.log(inputValue); // Log the value when the user submits
};
return (
<View>
<TextInput
ref={inputRef}
onChangeText={(e) => (inputRef.current.value = e)} // Store the value in the ref
placeholder="Enter text..."
style={{ borderBottomWidth: 1, padding: 8 }}
/>
<Button title="Focus" onPress={focusInput} />
<Button title="Clear" onPress={clearInput} />
<Button title="Submit" onPress={handleSubmit} />
</View>
);
};
export default InputExample;
React Native Hub1 862
I've just published a new article
Check it out and let me know your thoughts! Your support means a lot. 🙌
👉 Read here: Why Every React Native Developer Should Understand useCallback
React Native Hub
1 862
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
1 862
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
1 862
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
name, email, 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 Hub1 862
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
1 862
🔹 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 Hub1 862
🎯 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 Hub1 862
🎨 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
1 862
🔒 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 Hub1 862
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 Hub1 862
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 Hub1 862
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 Hub1 862
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