Props are read-only attributes that are passed from a parent component to a child component. They allow data and event handlers to be sent to child components.
State: Think of state like local variables in a function. They are declared and managed within the component.( or State: It's a way to keep track of information or data within a component. This information can change over time as the user interacts with the app or as data is updated.)
(State:Each component can have its own state. This means the data stored
in the state is only available to that specific component.)
2.When will you use state, context, and external state
manager?
(i). STATE:Local State: Use state for managing local
component data. This is data that is specific to one component and doesn't need
to be shared with other components.
In Realtime used in: Simple
Applications:
For simple applications or components where the state is not deeply nested and
doesn't need to be shared widely.
(ii). CONTEXT:Global State: Use context for managing global state that needs
to be accessible by many components at different levels of the component tree.
In Realtime used in :Theming,
Auth, Settings:
Common use cases include theming, authentication, and user settings.
(iii). External State Manager
When to Use:
- Complex
State Management: Use an external state manager like Redux or MobX for
managing complex state that involves deeply nested data, multiple sources
of truth, or when you need advanced features like middleware.
Large Applications: Ideal for large applications with a lot of state that needs to be shared across many components and modules.
For State example refer QA -1
Below are the Context and Reducer code examples
Example
with Redux:
---------------------------------------------Question:3-----------------------------------------------------
3. How do you decide when to split a component into subcomponents?
Benefits of Splitting Components
- Improved Readability: Smaller, focused components are easier to read and understand.
- Reusability: Components can be reused across different parts of the application.
- Maintainability: Easier to manage, debug, and test smaller components.
Final Thoughts
Splitting components should be driven by the need to simplify, reuse, and maintain your codebase. It’s a balance between having too many tiny components and overly large, complex ones. If it improves your code, it’s usually the right decision.
I hope this helps clarify when to split a component into subcomponents! If you have more questions, feel free to ask!
Guidelines for Splitting Components
Single Responsibility Principle: Each component should ideally have one responsibility. If a component is doing too many things, consider splitting it.
Example: A component that handles both user authentication and displaying user profile information can be split into separate
Auth
andUserProfile
components.
Reusability: If a piece of UI or logic is used in multiple places, it should be a separate component.
Example: A
Button
component that is used in various forms throughout the app.
Complexity Management: If a component grows too complex or large, making it difficult to understand, it's time to split it.
Example: A
Dashboard
component with multiple sections (charts, tables, notifications) can be broken down intoChart
,Table
, andNotification
components.
Separation of Concerns: Different concerns or functionalities should be handled by different components.
Example: A
Form
component that handles form submission logic and form field rendering can be split intoForm
andFormField
components.
Readability: If splitting a component makes the code easier to read and understand, it’s a good decision.
Example: A complex
Header
component with navigation, search bar, and user menu can be split intoNav
,SearchBar
, andUserMenu
components.
Logical Grouping: Group related logic and UI together in separate components.
Example: A
ProductPage
component with product details, reviews, and related products can be split intoProductDetails
,ProductReviews
, andRelatedProducts
components.
Handling API calls in React involves choosing the right approach depending on whether the API should be called upfront (e.g., on component mount) or based on a user action (e.g., clicking a button). Let's break down both scenarios:
1. Calling APIs Upfront
When you need to fetch data as soon as a component mounts, you can use useEffect
along with a data-fetching function. This is common for loading data required to render a component.
2. Calling APIs Based on User Action
When you need to fetch data based on a user action, such as clicking a button, you handle the API call inside an event handler.
EXAMPLE FOR 1 AND 2
- Techniques and Best Practices
- 1. Error Handling: Always handle errors gracefully,
providing feedback to the user.
- Try/Catch: Use try/catch blocks to catch and
handle errors.
- Error States: Maintain an error state to
display error messages.
- 2. Loading States: Provide visual feedback while
data is being fetched.
- Loading Indicators: Show a loading spinner or
message when fetching data.
- 3. Data Caching: Use libraries like React Query or
SWR for caching and synchronizing data.
- 4.Debouncing/Throttling: Use debounce or throttle techniques for input-based API calls to prevent excessive requests. Refer below image for 3 & 4 point
---------------------------------------------Question:5-----------------------------------------------------
5.Explain some realtime usecases for Lodash.Debounce?
Lodash Debounce-is particularly useful in scenarios where you want to limit the frequency of events like user input or window resizing to improve performance and user experience.
/(Using lodash.debounce
in these ways helps improve performance and user experience by preventing functions from being called too frequently in response to rapid events.)
- Here are some typical usecases:
Using lodash.debounce
helps in controlling how often a function runs, especially during rapid actions like typing or scrolling. It waits a set time after the last action before running the function, preventing it from being called too often. This makes the app smoother and more efficient.
1.Search Input
When using a search bar, `
lodash.debounce
` optimizes performance by delaying the execution of the search function until the user stops typing for a brief moment. This reduces the number of API calls, preventing the function from running on every keystroke. It ensures efficient use of resources and smoother user experience. Essentially, (Debouncing the function or It) helps reduce the number of API calls, making the application more efficient. Explanation: Search Input
1.When you type into a search bar, `lodash.debounce` ensures your computer waits a bit before reacting. Instead of sending search requests with every keystroke, it pauses and sends them only after you stop typing for a short while. This way, it reduces unnecessary work and makes the app run more smoothly. Think of it as giving your computer a break to catch up!
or 2.When users type into a search input, it can trigger API calls to fetch search results. Debouncing the function helps reduce the number of API calls, making the application more efficient.
2.Window Resize
Window Resize: When handling window resize events, debouncing can prevent the function from being called excessively, which can lead to performance issues.
Explanation: Window Resizing
or Handling window resize events can be costly if done frequently. Debouncing the resize handler ensures the function is called less often, improving performance
3.Form Validation:
Form Validation: For forms with real-time validation, debouncing can help limit the frequency of validation checks, making the form more responsive and reducing unnecessary processing.
'or Real-time form validation can be improved by debouncing validation functions, reducing the frequency of validation checks.
Clear Explanation
When you're working with forms that validate input in real-time (such as checking if an email is valid while the user types), every keystroke can trigger a validation check. This can lead to a lot of unnecessary processing and can make the form less responsive.
Using Debouncing:
Debouncing helps by waiting for a short period after the user stops typing before performing the validation check. This way, the validation function isn't called on every keystroke, but rather once the user has paused for a moment.
Explanation: Debouncing
UserWithout Debouncing:
- User types a 10-character email.
- Validation function is called 10 times.
With Debouncing (e.g., 300ms delay):
- User types a 10-character email.
- Validation function is called once, 300ms after the user stops typing.
4.Debouncing Sroll
Debouncing scroll events can significantly improve performance in React applications by limiting the rate at which a function is executed while scrolling. This is particularly useful when handling operations like infinite scrolling, animations, or updating UI elements based on scroll position.
or Debouncing scroll event handlers helps prevent performance issues caused by frequent function calls during scrolling.
5.Autocompletion
Using debounce for autocompletion features helps limit the number of API calls as the user types.
Using lodash.debounce in these scenarios helps in improving performance by reducing the number of times a function is called, thereby optimizing resource usage and providing a better user experience.
Examples for above listed 5 usecases :
Refer: https://codesandbox.io/p/sandbox/lodash-debounce-nlhz38
Image1:Form validation and Search Functionality:
Image 2: Scroll and Resize
Image 3: autocomplete
No comments:
Post a Comment