1 - Render lists in ReactJS
To render the list of desserts in ReactJS, you can create a functional component and use the map method to iterate through the array and render each item as a list item. Here's how you can achieve that:
Each list item displays the dessert's name, calories, and creation date. We use the <hr /> tag to add a horizontal line between each dessert entry for better visual separation.
To render the list of desserts in ReactJS without using the map function, you can manually create the elements in the component's JSX code. Here's how you can achieve that:
In this example, we manually create each list item (<li>) for every dessert in the desserts array. We access each dessert's properties (name, calories, and createdAt) using array indexing (e.g., desserts[0].name for the first dessert).
However, keep in mind that using map is generally a better approach when rendering lists dynamically, as it avoids code repetition and automatically handles any changes in the number of elements in the array.
2 - Keys
In React.js, "keys" are a special attribute used to uniquely identify elements in a list of components or elements. When rendering a list of items, React needs a way to keep track of each individual item in the list and efficiently update and reorder them when needed (or add a new item in correct place). The "key" prop serves this purpose.
Example of using keys in React when rendering a list of components:
In this example, we're rendering a list of items using the map function. Each item has a unique id, which we use as the key prop for each li element. React will use these keys to efficiently update the list when necessary.
Cautionary Advice
When assigning keys to items in a list, avoid using the item's index in the array as the key. React will use the index as the default key if none is specified, but this can lead to issues when the list's order changes due to insertions, deletions, or reordering. Relying on the index as a key can result in subtle and confusing bugs.
Likewise, refrain from generating keys on the fly, such as using key={Math.random()}. This approach will cause keys to be different between renders, causing React to recreate all components and the corresponding DOM each time. This not only impacts performance but also leads to the loss of user input inside list items. Instead, opt for stable IDs based on the data.
While generating unique IDs using methods like uuidv4() or Math.random() will prevent collisions and create unique keys, it can lead to the problem of React recreating the list items from scratch during re-rendering. This happens because the keys are different between renders, and React treats the elements as entirely new components.
Keep in mind that components won't receive the key as a prop. React uses the key internally as a hint for efficient updates. If your component requires an ID, you must pass it as a separate prop, like this: <Profile key={id} userId={id} />.
Key Rules:
Uniqueness among siblings: Keys must be unique among elements within the same level of the component's rendering. Each sibling in an array of elements should have a distinct key to enable proper identification and efficient updates.
Reusable keys in different arrays: It is acceptable to use the same keys for JSX nodes that belong to different arrays. Keys only need to be unique within the context of their siblings.
Immutable keys: Keys must remain constant and not change during the component's lifecycle. Modifying keys defeats their purpose and can lead to unexpected behavior. Avoid generating keys dynamically while rendering.
In summary, use unique and unchanging keys among sibling elements to ensure proper identification and efficient rendering of components in React. Avoid generating keys dynamically during rendering to maintain stability and avoid potential issues.
3 - Uncontroled vs Controled Components
In React.js, controlled components and uncontrolled components are two different strategies for managing form elements and their state. Controlled components use React's state management to control the form element's value and behavior through the value and onChange props. Uncontrolled components, on the other hand, let the form element maintain its own internal state and use ref to access its value. Each approach has its use cases and can be chosen based on the specific needs of the application.
Example 1: Uncontrolled Component
Uncontrolled inputs are similar to regular HTML form inputs. They retain the typed content using the DOM's internal state. To access their value, use a React ref. In the code below, a ref is used to get the input value upon form submission.
Uncontrolled Components Explanation (in 3 steps):
1. Input Ref:
The code uses the useRef hook to create an inputRef. This inputRef is used to reference the input element in the form.
2. Uncontrolled Input:
The input element is an uncontrolled component since it does not rely on React's state management. Instead, the input's value is managed by the DOM itself.
3. Form Submission:
When the form is submitted, the handleSubmit function is called. It accesses the value of the input using inputRef.current.value, allowing you to do something with the input's value. Since it's uncontrolled, React doesn't track or manage the input's state.
Uncontrolled components with refs are fine if your form is incredibly simple regarding UI feedback. However, controlled input fields are the way to go if you need more features in your forms.
Evaluate your specific situation and pick the option that works best for you.
The below table summarizes the features that each one supports:
Using the Context API in React allows you to manage global state and share data between components without the need to pass props down through the component tree.
The Context API in React is a powerful tool for managing state at the component level and making data available throughout the component tree without the need for prop drilling.
Here's a step-by-step guide on how to implement the Context API in React:
Demonstration of the context API - Toogle Theme (Light and Dark):
1. Create a context
2. Consume the Context Provider
3. Wrap the App with the context Provider(and with second step too!!):
And, the result of application will be:
Others application:
Here are five real-world applications of the Context API in React:
Theme Switching:
Context API can be used to implement a theme switching functionality in your React application. By creating a ThemeContext, you can store the current theme (e.g., light or dark) and provide it to all components that need to be styled accordingly. Components can access and update the theme state without having to pass it down through props explicitly.
Internationalization (i18n):
For applications with multilingual support, the Context API can be used to manage the current language and provide translations to various components. By creating a LanguageContext, you can store the selected language and the corresponding translation dictionary. This way, components can access the language and translation data to render content in the appropriate language without needing to pass it down through props.
Authentication and User Data:
Context API can be utilized to handle user authentication and store user-related data throughout the application. By creating an AuthContext, you can store user information, such as the authenticated state, username, email, and other relevant data. Components that need access to this information (e.g., user profile, dashboard) can consume it directly from the context, simplifying the process of checking authentication status and fetching user data.
Notification System:
Implementing a notification system in your React app becomes more manageable with the Context API. By creating a NotificationContext, you can manage the display of notifications (e.g., success, error, warning) and their content throughout the app. Components can then trigger notifications by updating the context, and other components that handle displaying notifications can listen to the changes and show them accordingly.
Shopping Cart and Checkout:
Context API can be used to manage the state of a shopping cart and facilitate the checkout process. By creating a CartContext, you can store the items in the cart, their quantities, and other related data. Components responsible for rendering the cart, handling item additions, updates, and removals can easily access and modify the cart state through the context.
These are just a few examples, but the Context API is versatile, and you can use it to manage various types of application-wide state and behaviors efficiently. Remember that it is recommended for managing moderate to small amounts of shared state, and for larger applications, you might consider using state management libraries like Redux or MobX.
Comments
Post a Comment