Interview Question
Interview Question
Key Features:
Why Hermes?:
React Native team made Hermes the default starting from React
Native 0.70.
Used in: Early versions of React Native (before 0.60 and optionally in
later versions).
Key Features:
Limitations:
Version 1
Not as fast as Hermes for mobile-specific use cases.
2. V8
Key Features:
Usage:
Key Features:
Limitations:
Key Comparisons
Optimized for
Engine Platform Performance Memory Usage
Mobile
Version 2
Verify in your android/app/build.gradle or ios/Podfile :
2. Switching Engines:
enableHermes: false
Conclusion
Hermes is now the default and preferred engine in React Native due to its
mobile-centric optimizations.
Advanced users can still opt for V8 or JSC based on specific needs.
1. JavaScriptCore (JSC)
Performance on Android:
Version 3
Android used a custom version of JSC (not updated frequently), leading
to performance and compatibility issues.
Startup Time:
Limited support for newer ES6+ features (until an updated version was
introduced in 2018).
Key Goals:
2. Memory Usage:
Version 4
Hermes had lower memory consumption due to its compact bytecode
and garbage collection optimizations.
Debugging Tools:
3. V8 (Optional, Community-Supported)
Problems V8 Solved
Version 5
High-Performance Apps:
Advanced Debugging:
WebAssembly Support:
It was used in React Native for Windows to integrate with the Windows
ecosystem efficiently.
Performance on Windows:
Version 6
Supported modern JavaScript features for compatibility with React Native.
Would you like guidance on how to enable specific engines or compare their
real-world performance? 😊
Why is Hermes the Current Default JavaScript Engine in React
Native?
The shift to Hermes as the default engine was a result of React Native's focus
on mobile-specific optimizations and the need to address key limitations of
previous engines like JavaScriptCore (JSC). Here's a detailed breakdown of
why Hermes is the current default and how it improves performance:
Version 7
High Memory Usage: JSC was not designed for resource-constrained
mobile devices, leading to inefficient memory use.
2. V8:
1. Performance Enhancements
Startup Time Reduction:
Memory Optimization:
Version 8
It prioritizes resource efficiency.
Performance Benchmarks
Startup Time
🔥 Faster (30-50% ❌ Slower due to runtime
improvement) parsing
Version 9
Eliminates the need for developers to configure the engine manually,
simplifying app development.
3. Enhanced Debugging:
In Summary
Hermes improves on the shortcomings of JSC by focusing on:
Mobile-specific optimizations.
It was chosen as the default engine because it aligns with React Native's
mission to deliver the best mobile experience on all devices, including low-
end ones.
Would you like to see how to enable or benchmark Hermes in your own React
Native project?😊
🚀 React Native's Significant Improvements
🆕 New Architecture in React Native 0.76
Version 10
📅 Released: October 2024
✨ Key Enhancements:
⚡ Full Support for Modern React Features:
Adds features like:
✨ Why It Matters?
React Native's focus on performance, developer experience, and modern
features ensures it remains a powerful framework for building cross-platform
mobile applications! 💻📱
Here are the engines commonly used in modern browsers that power React.js
applications:
Key Features:
Version 12
Why It's Important for React:
Key Features:
Key Features:
Key Features:
Version 13
Optimized for Windows systems.
Was important for React apps targeting older versions of Edge but is
now obsolete.
V8, SpiderMonkey, and JSC are all optimized to support React’s modern
asynchronous features.
2. WebAssembly Integration:
Conclusion
The choice of the JavaScript engine for React.js depends on the browser:
Certainly! Here's a list of libraries and modules that can be used in JavaScript
as well as React Native, along with brief explanations for each:
Version 14
🔧 Libraries/Modules Usable in Both JavaScript & React Native
1. Lodash
Purpose: Utility library for working with arrays, objects, strings, etc.
Example:
2. Moment.js / Day.js
Purpose: Date and time manipulation.
Example:
3. Axios
Purpose: HTTP client for making API requests.
Example:
axios.get('https://jsonplaceholder.typicode.com/posts')
Version 15
.then(response => console.log(response.data))
.catch(error => console.error(error));
Example:
store.dispatch(counterSlice.actions.increment());
console.log(store.getState()); // 1
5. React Query
Purpose: Server state management and data fetching.
Example:
function App() {
Version 16
const { data, error, isLoading } = useQuery(['posts'],
() =>
fetch('https://jsonplaceholder.typicode.com/posts').
then(res => res.json())
);
return (
<FlatList
data={data}
renderItem={({ item }) => <Text>{item.title}</Text
>}
/>
);
}
6. Styled Components
Purpose: CSS-in-JS for styling.
Example:
function App() {
return <StyledButton title="Press Me" />;
}
7. Formik
Purpose: Form management.
Version 17
Use Cases: Handling form validation and state.
Example:
function App() {
return (
<Formik
initialValues={{ name: '' }}
onSubmit={values => console.log(values)}
>
{({ handleChange, handleSubmit, values }) => (
<TextInput
onChangeText={handleChange('name')}
value={values.name}
onSubmitEditing={handleSubmit}
/>
)}
</Formik>
);
}
8. Yup
Purpose: Schema validation.
Example:
Version 18
.catch(err => console.error(err.errors)); // ["Name is
required", "Age must be greater than or equal to 18"]
Example:
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
Example:
function App() {
Version 19
return (
<VictoryBar
data={[
{ x: 1, y: 2 },
{ x: 2, y: 3 },
{ x: 3, y: 5 },
]}
/>
);
}
Would you like to dive deeper into the implementation of any of these libraries?
Answer:
Examples:
Version 20
Axios : A popular library for making HTTP requests.
2. Native-Specific Libraries/Components:
Examples:
3. DOM-Specific Libraries:
Components or libraries that use window , document , or any DOM API are
JavaScript-specific because the DOM exists only in the browser.
React Native does not use a DOM. Instead, it uses a virtualized UI layer
that maps React Native components (like View , Text , etc.) to native
mobile components.
Examples:
4. Polyfills/Bridging Libraries:
Some libraries bridge the gap between the browser and React Native by
implementing polyfills or fallback mechanisms.
Example:
5. Key Takeaway:
Version 21
❌ Mistakes to Avoid While Answering:
1. Oversimplification:
The original answer lacked examples and nuance. Simply stating, "If
it's pure JavaScript, it works for both; otherwise, it's platform-specific,"
is incomplete.
3. Misuse of Terms:
Version 22
4. Structure Your Answer:
The response was not structured, which can make it hard for an
interviewer to follow or assess knowledge.
It’s not just about being correct but also showing depth of understanding.
Would you like me to create a more concise version of this for quick notes?
Version 23
to iOS (which uses the highly optimized JavaScriptCore engine).
Key Notes:
Enabling Hermes is optional but highly recommended for most React Native
apps.
Misconceptions:
Hermes is not specific to Android or iOS; it works on both.
The default engine for iOS is JavaScriptCore, but Hermes can replace it for
optimized performance.
Would you like me to explain how to enable Hermes in a React Native project?
Answer Example:
Version 24
"I haven’t had the opportunity to work directly on iOS React Native
development because I currently develop on a Windows environment and don’t
have access to an iOS device for testing. However, I’m familiar with the process
of enabling Hermes on both Android and iOS in React Native. From what I
know, Hermes is supported on both platforms and is typically enabled through
the project configuration. I would be happy to work with the team to ensure
that Hermes is properly set up on iOS if needed."
2. Proactive Knowledge: You show awareness of Hermes and its role in both
Android and iOS development, even though you haven’t personally worked
on iOS.
3. Positive Outlook: You express a willingness to learn or work with the team
to ensure Hermes is set up on iOS. This demonstrates flexibility and a
growth mindset.
Mistake to Avoid:
Avoid sounding like a limitation. Instead of focusing only on the fact that
you don’t have an iOS device, focus on your proactive learning and how
you would overcome such challenges in the future.
This approach gives the impression that you are problem-solving and ready to
take on new tasks even if they are outside of your current experience.
2. Update Podfile :
Version 25
Add the following line to enable Hermes for iOS:
3. Install Pods:
cd ios
pod install
4. Clear Cache:
Version 26
Common Issues:
Ensure your Xcode version is compatible with the version of React Native
you're using. Sometimes, issues can arise due to version mismatches.
Would you like a more detailed explanation of any step or encounter any
specific issue during setup?
Detailed breakdown of what happens when you modify the Podfile to enable
Hermes in iOS for React Native.
target 'YourApp' do
config = use_native_modules!
At this point, the default JavaScript engine ( JavaScriptCore ) will be used for the
iOS build.
Version 27
platform :ios, '10.0'
target 'YourApp' do
config = use_native_modules!
The default setting uses the JavaScriptCore engine (iOS's native JS engine),
and Hermes isn’t enabled in this case.
Explanation:
:path => config[:reactNativePath] : This specifies the location of the React
Native source code.
1. Install Pods:
Version 28
cd ios
pod install
Summary:
Before: The Podfile simply uses use_react_native! without enabling Hermes,
which defaults to JavaScriptCore.
Would you like any further clarification or help with another part of the setup?
Smart Components are responsible for more than just rendering UI.
They handle state management and logic. They often connect to stores
(like Redux) or APIs to fetch data.
2. Features:
Version 29
State Management: Smart Components manage state locally and are
responsible for handling user interactions, form inputs, etc.
Business Logic: They can contain logic for how data is processed or
manipulated.
Side Effects: They often interact with external systems (e.g., network
requests, subscriptions, timers) and use hooks like useEffect to manage
side effects.
Example: A Smart Component can fetch data from an API, store it in its
local state, and pass it down to presentational components for
rendering.
3. Example:
useEffect(() => {
fetchData();
}, []);
Version 30
1. Purpose:
2. Features:
Receive Props: They are typically passed data from Smart Components
(or parent components) through props.
3. Example:
Key Differences:
Aspect Smart Component Dumb Component
State
Handles its own state No internal state
Management
Version 31
Props Passes data to Dumb Components Receives data via props
Dumb Components should not contain logic: The main job of a Dumb
Component is to render UI based on props. If it starts containing logic, it’s
no longer a "Dumb Component" in the pure sense, which can lead to
difficulties in maintaining the code.
In summary:
Would you like further examples or deeper insights on how these components
interact?
What is InteractionManager?
InteractionManager in React Native is designed to help manage and schedule
tasks in a way that minimizes blocking the UI thread. It allows you to schedule
tasks to be executed only after animations or interactions (like scrolls,
gestures, or transitions) have completed, keeping the UI smooth and
responsive.
Version 32
How does InteractionManager Work?
Scheduling tasks: You can use InteractionManager to defer tasks like API
calls or heavy computations so that they don’t block the UI thread during
animations or transitions.
Why is it Important?
Performance: It helps in keeping the UI smooth and responsive by
offloading time-consuming tasks like API calls, calculations, or data
processing to be done after UI updates are complete.
Prevent Jank: By ensuring that the main thread (UI thread) is only dealing
with UI-related tasks, you prevent UI jank or lag during animations and
transitions.
useEffect(() => {
// Start animation
Animated.timing(fadeAnim, {
toValue: 1,
duration: 2000,
useNativeDriver: true,
}).start();
Version 33
InteractionManager.runAfterInteractions(() => {
// This will be executed after all animations and int
eractions finish
fetchDataFromAPI();
});
}, []);
return (
<View>
<Animated.View
style={{
opacity: fadeAnim,
}}
>
<Text>Animating...</Text>
</Animated.View>
</View>
);
};
executed after the animation finishes. This ensures that the animation runs
smoothly without being blocked by the API call.
fetchDataFromAPI : This function handles the API request, but it won’t run until
all animations or user interactions are completed.
Version 34
When to Use InteractionManager?
Heavy computations: If you’re performing CPU-intensive tasks, like
complex calculations, and you want to avoid blocking the UI.
API calls: If you need to make network requests but don’t want them to
interfere with animations or interactions.
Heavy data processing: When you need to process large datasets but don’t
want it to impact user experience.
Conclusion:
InteractionManager helps in managing tasks that would normally block the UI
thread, making sure that your animations and UI remain smooth and
responsive. It’s particularly useful in scenarios where you have animations and
heavy tasks running in parallel.
Would you like further insights on other performance optimization strategies in
React Native?
2. Benefits:
Version 35
Design Consistency: Since these components are reusable, you ensure
consistent UI throughout the application. For example, if you have a
button component, you can use it everywhere in your app. If you need
to change its style (e.g., change the color from blue to red), you only
need to do it in one place.
Example:
2. Benefits:
Example:
Version 36
return (
<div>
<Button color="blue" onClick={increment} label="In
crease" />
<Button color="blue" onClick={decrement} label="De
crease" />
</div>
);
};
1. Key Problem:
If both buttons are part of the same component and you only want the
button related to the salary to re-render when it is clicked, you need to
make sure that the components are properly isolated and optimized. React
will re-render all components that use the state that has changed.
Version 37
<button style={{ backgroundColor: color }} onClick=
{onClick}>
{label}
</button>
);
});
return (
<div>
<Button color="blue" onClick={() => setSalary(sala
ry + 100)} label="Increase Salary" />
<Button color="green" onClick={() => setSalary(sal
ary - 100)} label="Decrease Salary" />
<Button color="blue" onClick={() => setCounter(cou
nter + 1)} label="Increase Counter" />
</div>
);
};
3. Key Takeaways:
Break down the state into smaller components, and use separate states
for different parts of the UI that don’t need to interact.
Version 38
Keep the answer simple and focused. Don’t go into unnecessary details
unless asked. Explain the core difference in terms of state
management and UI rendering.
Summary:
Presentation Components = Stateless, reusable, focused only on UI.
If you follow this approach, your response will be clear, structured, and
demonstrate good understanding of React principles. Would you like further
clarification on any of these concepts?
2. Key-Value Pair:
Data in AsyncStorage is stored as a key-value pair, making it easy to
retrieve and set values based on keys.
3. Non-Secure:
Version 39
One important thing to note is that AsyncStorage is not encrypted,
meaning that the data stored in it is not secure and can be accessed by
someone with the necessary tools, especially if the device is compromised.
// Save data
const saveData = async () => {
try {
await AsyncStorage.setItem('@user_token', 'some_token_v
alue');
console.log('Token saved!');
} catch (error) {
console.error('Failed to save token', error);
Version 40
}
};
// Retrieve data
const getData = async () => {
try {
const token = await AsyncStorage.getItem('@user_toke
n');
if (token !== null) {
console.log('Token:', token);
}
} catch (error) {
console.error('Failed to retrieve token', error);
}
};
// Remove data
const removeData = async () => {
try {
await AsyncStorage.removeItem('@user_token');
console.log('Token removed!');
} catch (error) {
console.error('Failed to remove token', error);
}
};
Important Notes:
1. Limitations: AsyncStorage is not ideal for storing large data sets. For larger
datasets, SQLite or Realm is a better option.
3. Not for Sensitive Data: As mentioned, avoid using AsyncStorage for secure
or private information. Use SecureStorage for encrypting sensitive data
before storing it.
Mistakes to Avoid:
Version 41
Using AsyncStorage for Secure Data: Don’t store sensitive data like
tokens, credentials, or personal information in AsyncStorage.
Not Handling Errors: Always handle errors (e.g., using try/catch) when
interacting with AsyncStorage, as operations might fail due to various
reasons (e.g., device storage full, app permissions, etc.).
Conclusion:
AsyncStorage is great for storing small, non-sensitive pieces of data
persistently across app sessions.
For sensitive data, always use secure storage solutions to protect user
data.
This approach ensures that you’re using the right storage system for different
types of data and optimizing both security and performance for your app.
Would you like to dive deeper into other secure storage options for React
Native?
component tree.
Version 42
Why setNativeProps is Useful:
This method is particularly useful in scenarios where you need to perform high-
frequency updates, such as during animations, gesture handling, or when
you're dealing with large lists of components (for example, 30 components as
you mentioned) and you want to avoid unnecessary re-renders.
In your case, where you want to animate a specific component (say, a button or
a box) without triggering re-renders of other components on the screen, using
setNativePropscan significantly improve performance by updating only the
native properties of that component without touching the rest of the UI.
const boxStyle = {
transform: [{ translateX: animatedValue }],
};
return (
<View>
<Text>My Animating Box</Text>
<Animated.View
style={[{ width: 100, height: 100, backgroundColor:
'blue' }, boxStyle]}
// Using setNativeProps to directly manipulate nati
Version 43
ve properties
ref={(ref) => ref && ref.setNativeProps({ style: {
backgroundColor: 'green' } })}
/>
<Button onPress={startAnimation} title="Start Animati
on" />
</View>
);
};
In this example, the setNativeProps method is used to directly change the style
Performance Implications:
1. Avoids Re-rendering:
The primary benefit of using setNativeProps is that it avoids re-rendering the
component and its children. React does not need to go through its diffing
and reconciliation process, which can be costly in terms of performance,
especially with complex UI trees or frequent updates.
3. Low-Level Updates:
By directly updating native properties, setNativeProps allows React Native to
perform lower-level optimizations at the native side, which are faster than
React’s JavaScript-based approach to updating the UI.
Version 44
UI. Therefore, it should be used sparingly and only when you have specific
performance concerns (e.g., during animations or gesture handling).
4. Error-Prone:
Since setNativeProps bypasses React’s normal flow, it can potentially lead to
bugs or inconsistencies, especially if the component state or props are not
correctly managed. Always ensure that the UI updates are well-controlled
to avoid UI mismatches.
Mistakes to Avoid:
Overuse: Relying too much on setNativeProps can lead to uncontrolled
components, making debugging more difficult.
Conclusion:
is an excellent tool for optimizing performance, especially in
setNativeProps
Version 45
Would you like further details or examples on using setNativeProps effectively in
specific scenarios?
Answer on setNativeProps Usage for Animation:
If you have a screen with 30 components and you want to perform an
animation (e.g., translate or scale a particular component), using setNativeProps
will prevent the entire screen from re-rendering. Instead, it directly updates
the native view without affecting the React component tree. This means only
the animated component will update, and performance improves because
React does not re-render the whole UI.
Example:
Scenario: You have 30 components on the screen.
Thank you for the clarification. Here's how you can frame the answer with a
quick and effective explanation, followed by a highlighted example for easy
recall:
1. Console.log:
2. Chrome Debugger:
You can inspect state, variables, and network requests, giving you a
comprehensive view of what's happening in the app.
Version 46
If you want to debug performance issues like memory consumption,
CPU usage, or network traffic, these tools are best suited for profiling.
Version 47
1. Over-explaining Basic Tools: Don’t spend too much time on very basic
tools like console.log unless the interviewer asks for it.
3. Being Vague: Simply mentioning tools without explaining when and why
you would use them can lead to a lack of clarity.
Helps catch bugs by testing your code before you run it.
Helps you find and fix issues during runtime by directly interacting with
the code.
Version 48
Offers breakpoints and real-time analysis of your app’s state and
behavior.
// simpleFunction.js
export const add = (a, b) => a + b;
// simpleFunction.test.js
import { add } from './simpleFunction';
Conclusion:
Jest is used for automated testing and helps you identify bugs by running
tests on your code, but it is not a tool for debugging.
For debugging real-node applications, you would use tools like Chrome
Debugger, Xcode, or Android Studio, which allow you to inspect and
modify your code during execution.
This combined explanation should help clarify the distinction between Jest and
debugging tools and how both serve different purposes.
Version 49
Best Practices for Testing React Native Applications:
Testing in React Native should follow a structured approach to ensure the
reliability of the application throughout the development process. Below is a
breakdown of best practices and testing tools:
Best Practice: Write tests for small units of functionality like functions
or components. Each test should be isolated from others to check that
specific functionality independently.
2. Integration Testing:
3. UI Testing:
Purpose: To test how the UI components behave and how the user
interacts with them.
Best Practice: Use tools like Jest and React Native Testing Library to
automate UI interaction tests such as button clicks, form submissions,
and UI rendering.
4. Mocking:
Version 50
Purpose: To simulate external dependencies (e.g., API calls) for unit
testing without actually performing the real operation.
5. Snapshot Testing:
Allows you to write unit tests, mock APIs, and even run UI tests.
Example:
// Function to test
export const add = (a, b) => a + b;
Version 51
Example:
3. Detox:
Useful for testing the full application flow, ensuring features work as
expected when interacting with the UI.
Example:
4. Cypress (For Web apps, but can be useful for cross-platform projects):
A web testing framework that can also be used for testing cross-
platform components like React Native Web.
Version 52
Q: How do you test React Native applications?
In React Native development, I follow a structured approach to testing, starting
with unit tests and moving on to integration tests and UI testing:
1. Unit Testing: First, I write unit tests for small units of functionality like
functions or components. I use Jest to test functions and methods for
expected behavior, making sure individual components or logic are working
in isolation.
4. Business Logic & UI Test Cases: I write test cases for business logic to
ensure calculations or API calls work correctly. For the UI, I focus on
making sure that components render as expected under different
conditions.
Tools I Use:
Jest for unit testing and mocking API calls.
Detox for end-to-end testing (E2E) when testing full app flows, like logging
in or completing a transaction.
Mistakes to Avoid:
1. Skipping Test Coverage: Don't skip writing unit or integration tests as they
are crucial for ensuring the correctness of your code before moving on to
other stages of development.
2. Testing Only Happy Paths: Make sure to test edge cases and error
handling scenarios, not just the typical use cases.
Version 53
3. Not Automating Tests: Manually running tests is time-consuming and
prone to error. Always aim to automate your tests as much as possible.
4. Mixing Test Types: Keep unit tests, integration tests, and UI tests distinct.
Unit tests should test isolated logic, integration tests should test how
components work together, and UI tests should simulate user interactions.
By following these practices and using the right tools, you can ensure a reliable
and bug-free React Native application.
Version 54
Image loading issues could be consuming too much memory. If images
are not properly released, they may pile up in memory.
FlatList in React Native is more efficient for handling large lists of data,
especially images.
Large images can increase both memory usage and loading times,
making the app slow.
Ensure that the images are optimized before they are sent from the
server:
Implement lazy loading for images. This ensures that images are
loaded only when they come into view.
Monitor the CPU usage during scrolling to see if the processor is being
overloaded.
Version 55
If you notice a spike in CPU usage, there could be an inefficient
algorithm running during the scroll. Check the event handlers,
animations, or image processing logic that might be consuming
unnecessary CPU resources.
1. Switch to FlatList:
Version 56
Use react-native-fast-image for faster image loading and caching:
In Xcode, use the Memory Leak Detector to check if any memory is being
leaked.
Conclusion:
Version 57
By following these steps, we can effectively reduce memory consumption and
optimize performance while scrolling through large lists in React Native. The
key action points are:
Monitor memory and CPU usage with Xcode and Android Studio.
These steps should prevent the app from crashing due to memory or
performance bottlenecks.
Example:
Version 58
uri: uri,
priority: FastImage.priority.normal,
}}
resizeMode={FastImage.resizeMode.cover}
/>
);
Example:
Version 59
}
};
Cache Location: It can store images in the app's cache directory and
provides tools to manage caching behaviors such as clearing the
cache, fetching images from the cache, etc.
Example:
Purpose: Allows for caching data in the form of files on the device.
Cache Location: Data is stored in the device's file system, which allows
for caching large objects (like files or images) that you can manage
yourself.
Example:
Version 60
const getCachedImage = async () => {
const filePath = `${RNFS.CachesDirectoryPath}/imag
e.jpg`;
const exists = await RNFS.exists(filePath);
if (exists) {
return filePath;
}
};
Store the cached images or files in the device's Caches directory. This
directory is intended for storing temporary files that can be cleared at any
time by the system if the device runs low on space.
SQLite databases can be used to store small data in tables with structured
queries. For more complex or persistent caching, this can be a good choice.
Version 61
const path = `${RNFS.CachesDirectoryPath}/${fileName}`;
await RNFS.writeFile(path, data, 'utf8');
};
For small data (such as user settings, tokens, etc.): Use AsyncStorage,
which saves data in the device's local storage.
For larger files or more complex data: Use react-native-fs to save files in
the Caches directory or implement a custom caching strategy based on
SQLite.
Important Considerations:
Always monitor your app’s memory consumption when caching images or
files, especially for large data.
By following these best practices, you can manage your app’s cache effectively
while ensuring good performance and efficient memory use.
In React Native, cache clearing depends on your app's design and the specific
data you're caching. By default, when you use third-party libraries like react-
native-fast-image or react-native-cached-image , they handle cache management for
Version 62
you. However, there are cases where you might need to implement cache
clearing manually to improve performance or handle storage issues.
For File Caching: If you're using react-native-fs to cache files, you can
delete the cached files manually.
Example with react-native-fs :
Version 63
const clearCache = async () => {
const cachePath = `${RNFS.CachesDirectoryPath}/image.j
pg`;
const exists = await RNFS.exists(cachePath);
if (exists) {
await RNFS.unlink(cachePath); // Delete cached imag
e
}
};
For AsyncStorage: You can clear specific keys or clear all cached data in
AsyncStorage.
Example:
Users clearing cache manually should be a last resort. If users need to clear
cache due to app issues (e.g., app slowdown or corrupted data), your app
may not be managing the cache effectively. Therefore, automatic clearing
and cleanup should be the preferred approach.
Summary:
In React Native, cache should generally be managed by the app, and you
should implement a strategy for clearing outdated or unnecessary cache.
Version 64
Manual cache clearing (by the user) should be avoided if possible, and
caching should be done efficiently to prevent issues like performance
degradation or storage overuse.
By implementing internal cache management and cleanup, you ensure your app
runs efficiently and provides a better user experience without requiring users to
manually clear cache.
Sure! Let's break down the answer and the key points related to performance
issues in React Native, and I'll clarify the part about arrow functions and
normal functions as well.
Version 65
component, a new styling object is created, leading to unnecessary
memory allocations.
Arrow Function:
When you use an arrow function inside the render method, React
creates a new function every time the component re-renders. This
can trigger re-renders in child components if those functions are
passed as props.
Normal Function:
Version 66
return <Button onPress={handleClick} />;
};
MyComponent.handleClick = () => {
console.log('Button clicked');
};
Key Takeaways:
Arrow functions inside render methods cause performance overhead due
to re-creation on every render.
By following these practices, you can ensure that your React Native app
performs efficiently and doesn't run into unnecessary re-renders, memory
issues, or processor bottlenecks.
Understood! If I were the interviewer, here's how I would break down and
evaluate the answer based on what's acceptable or satisfiable, and what you
Version 67
can do to give a better response than the student who answered previously.
This is a good start, but the explanation lacks specific solutions for
optimizing performance beyond general knowledge.
The student mentions the issue with inline arrow functions, which is a
valid point. However, the explanation could be improved by:
However, they should have added more emphasis on how inline styles
cause re-creation of the style object on every render, which consumes
extra memory and processing power.
4. FlatList Example:
Version 68
What I, as the Interviewer, Would Want to Hear (Better
Answer):
A more satisfying answer would be one that:
1. Clearly explains how re-renders happen due to inline functions, and how
reusing references (for functions and styles) can optimize performance.
Perfect Answer:
Version 69
very render
return <Button onPress={handleClick} />;
};
Version 70
container: {
marginTop: 10,
padding: 20,
},
});
const MyComponent = () => {
return <View style={styles.container} />;
};
Version 71
Inline styling: Causes new style objects to be created on each render,
which can be avoided by using StyleSheet.create .
FlatList: Efficient rendering of large lists by rendering only the visible items
and unloading off-screen items.
Performance profiling tools: Use Xcode and Android Studio for analyzing
memory usage, processor consumption, and overall performance.
Conclusion:
In order to satisfy the interviewer, the answer needs to be detailed, technical,
and should include practical examples. Explaining the core issues and offering
specific solutions with references to tools or best practices like FlatList,
StyleSheet, and memoization will make your answer more complete and
showcase your deeper understanding of performance optimization in React
Native.
Here’s a structured breakdown of the key points and how you can present the
answer effectively for your React Native interview preparation:
2. Code Reusability:
Version 72
React Native simplifies the process of building responsive UI, offering
pre-built components and supporting UI consistency across platforms.
7. Modular Architecture:
8. Ready-Made Solutions:
Combines web and native app characteristics, built with HTML, CSS,
and JavaScript, then wrapped into a native app container.
Native Apps:
Version 73
React Native is a cross-platform mobile development framework that
allows developers to write code in JavaScript while producing apps that
use native UI components.
React Native allows you to build apps for both Android and iOS without
needing to learn Java or Swift.
Instead of directly manipulating the actual DOM (which can be slow), React
uses the VDOM to optimize updates by keeping the UI representation in
memory.
Reconciliation is the process where React compares the real DOM with the
virtual DOM and updates only the parts of the UI that have changed.
Manipulating the VDOM is faster because it’s like editing a blueprint before
applying it to the real structure.
Real-World Context: You can further explain how these benefits play out in
real-world development scenarios, which will be helpful during your
interview.
Concise and to the Point: The answer is brief yet informative, ensuring that
you cover all important aspects without overwhelming the interviewer with
too much detail.
Version 74
Here’s a list of the most commonly used React Native libraries along with
some third-party libraries and their primary uses. This will help you get familiar
with the tools and packages that are widely used in React Native development.
Details: Allows stack, tab, and drawer navigation, and is widely used in
React Native apps for routing and navigation.
Version 75
Details: Integrates with Google Maps, Apple Maps, and other map
providers to show maps, markers, polygons, and other map features.
Details: Useful for retrieving device details like model, operating system
version, device name, and more.
Details: Provides full Firebase support for React Native apps, including
authentication, analytics, messaging, storage, and more.
Version 76
Details: Contains a large collection of icons from popular icon libraries
like FontAwesome, Ionicons, MaterialIcons, etc.
Details: Lets you display web pages inside a native view in your app,
useful for embedding third-party content or web-based features.
Version 77
13. React Native Clipboard
Details: Allows you to read from and write to the device's clipboard,
useful for copying and pasting data.
Details: Supports both push and local notifications for iOS and Android,
helping to send notifications at scheduled times or events.
Avoid overloading your app with too many libraries. Choose only the
ones that solve specific problems in your app.
Regularly check for updates to the libraries you are using. This ensures
bug fixes, security patches, and compatibility with the latest React
Native versions.
3. Be Mindful of Performance:
Version 78