0% found this document useful (0 votes)
11 views

React

summary react

Uploaded by

Maryem Raiahi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

React

summary react

Uploaded by

Maryem Raiahi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1

React Props
Using a variable directly from the global scope in the App
component, and again in the List component could work if you
only had one variable, but it doesn’t scale with multiple variables
across multiple components from many different files.

Using props, we can pass variables as information from a parent


component to child component and not vice versa.
It prevents the list variable from polluting the global scope when
defined outside of the component.

The child component receives an object parameter (props) which


includes all the passed attributes as properties (props).

React State
React state is used to make applications interactive,
to alter information over time.
React offers us a utility function called useState
React’s useState hook takes an initial state as an
argument (empty string). Providing this initial state to useState
→ Telling React that this state will change over time.
This function will return an array with two values.
The first value (searchTerm) represents the current state;
the second value is a function to update this state (setSearchTerm)
Steps:
- When the user types into the input field, the input field’s
change event is captured by the event handler.
- The handler’s logic uses the event’s value and the state
updater function to set the updated state.
- After the updated state is set in a component, the component
renders again (the component function runs again).
- The updated state becomes the current state
and is displayed in the component’s JSX.
2

Callback Handlers in JSX


A callback function
•gets introduced (A)
•is used elsewhere (B)
•“calls back” to the place it was introduced (C)

Search component can use this callback handler from its incoming props to call it whenever a user types into
the HTML input field

When an (event) handler is passed as props from a parent component to its child component, it becomes a
callback handler. React props are always passed down the component tree callback handlers passed as
functions in props can be used to communicate up the component hierarchy.

Lifting State in React


Currently, the Search component still has its internal state.
While we established a callback handler to pass information
up to the App component, we are not using it yet. We need
to figure out how to share the Search component’s state
across multiple components.
The search term is needed in the App to filter the list before
passing it to the List component as props.
We’ll need to lift state up from Search to App component to
share the state with more components.
The Search component doesn’t manage the state anymore,
but only passes up the event to the App component after text
is entered into the input field. You could also display the
searchTerm again in the App component or Search
component by passing it down as prop.
3

Always manage the state at a component where


every component that’s interested in it is one that
either manages the state (using information
directly from state) or a component below the
managing component (using information from
props). If a component below needs to update the
state, pass a callback handler down to it (see Search
component). If a component needs to use the state
(e.g. displaying it), pass it down as props.

By managing the search feature state in the App


component, we can finally filter the list with the
stateful searchTerm before passing the list to the
List component.

The filter function checks whether the searchTerm


is present in our story item’s title.
If the function returns true, meaning the condition
is met, the item stays in the newly created array;
if the function returns false, it’s removed.

The filter function still too opinionated about the letter case. If we search for “react”, there is no filtered
“React” story in your rendered list. To fix this problem, we have to lower case the story’s title and the
searchTerm:

React Controlled Components


Controlled components are not necessary React components, but HTML elements.
After giving the searchTerm an initial state (“react”), the list has been filtered according to the initial search,
but the input field doesn’t show the initial searchTerm.
We want the input field to reflect the actual searchTerm used from the initial state; but it’s only reflected
through the filtered list. (the athor item is removed)
We need to convert the Search component with its input field into a controlled component. So far, the input
field doesn’t know anything about the searchTerm. It only uses the change event to inform us of a change.
Actually, the input field has a value attribute.
4

Unidirectional data flow


1/ React components start with initial state, which may or may not be passed as props to child components 2/
UI is rendered for the first time
3/ User interactions or data loading trigger state change in React
4/ Parent components are notified via callback handler
5/ Components with modified state and all components below them are re-rendered
Component Lifecycle
At first, all components are instantiated from the top to the bottom of the component hierarchy. This includes
all hooks (e.g. useState) that are instantiated with their initial values (e.g. initial state). From there, the UI
awaits side-effects like user interactions. Once state is changed (e.g. current state changed via state updater
function from useState), all components affected by modified state/props render again.
React useState Hook
- Each run of a component function takes the most recent value from useState
- useState Hook doesn't reinitialize with initial value
- Hooks initialize only once when component first renders
- React tracks hooks internally with most recent values
Props Handling: Advanced React Techniques for Passing Props
Advanced techniques can make source code more concise, but not required for building complete React
applications
React props are a JavaScript object, accessed in components using props.propertyName.
Since props is an object which just passes information from one component to another component, we can
apply a couple JavaScript tricks to it. For example, accessing an object’s properties with modern JavaScript
object destructuring
JavaScript object destructuring
It allows us to extract data from an object in a more concise and readable way. Spring 2023 TBS - CS220 13
Basic syntax Object destructuring is done using curly braces.
const myObj = {name: "John", age: 30};
const {name, age} = myObj;
Object destructuring can also be used on nested objects.
const myObj = {person: {name: "John", age: 30}};
const {person: {name, age}} = myObj;
The two previous examples will create two variables, name and age, with their values set to "John" and 30
respectively.
You can also rename variables when destructuring objects by using a colon and the new variable name.
const myObj = {name: "John", age: 30};
const {name: fullName, age: years} = myObj;
This will create two variables, fullName and years, with their values set to "John" and 30 respectively.
Apply the destructuring of the props object in the component’s function body

OR
5

Nested destructuring in React components


The item parameter in the Item component is a JavaScript object.
The item object has been destructured from the props object
in the Item component's function signature.
The item object only passes its information (object properties)
to the elements in the component.
Nested destructuring can be used to gather all the necessary
information of an object in the function signature for
immediate usage in the component's elements.
However, it can introduce clutter through indentations in the
function signature, making it less readable. Despite this, nested
destructuring can still be useful in other scenarios.
Summary of JavaScript Object Destructuring
JavaScript object destructuring is commonly used not only for
the props object but also for other objects like the item object.
Nested destructuring can be used, but it didn't add any benefits in
our case and just made the component bigger.
Nested destructuring may be useful in different scenarios.
React Side-Effects
Side-effects are used to interact with APIs outside of the component and don't directly change the
component's output. Examples of side-effects include interacting with the browser's localStorage API, remote
APIs for data fetching, and measuring HTML element dimensions.
Next we’ll add a feature to our Search component in the form
of another React hook.
We’ll make the Search component remember the most recent
search interaction, so the application opens it in the browser
whenever it restarts.
First, use the local storage of the browser to store the searchTerm
accompanied by an identifier. Next, use the stored value, if there
a value exists, to set the initial state of the searchTerm.
Otherwise, the initial state defaults to our initial state
(here “React”) as before
Local Storage
- Local storage is a feature of web browsers that allows web applications to store data locally on a user's
device. It provides a simple key-value storage mechanism that can be used to persist data across browser
sessions.
- Local storage is a part of the Web Storage API, which also includes session storage. Local storage is
persistent, meaning that data stored in local storage will persist even after the user closes their browser or
navigates away from the website.
- Local storage is limited to 5-10 MB depending on the browser.
- Local storage is accessed using the localStorage object in JavaScript.
6

Using Local Storage


- To store a value, you can use the setItem() method, which takes a key and a value as arguments.
- To retrieve a value, you can use the getItem() method, which takes a key as an argument and returns the
corresponding value.
- You can also remove an item from local storage using the removeItem() method.
Example: localStorage.setItem('name', 'John'); => to store a user's name
const name = localStorage.getItem('name'); => To retrieve the name
Flaw in the Current Search Component Implementation
The handler function responsible for updating the state is also
managing the side-effect of storing the search term in the
local storage.
This approach can introduce bugs in the long run if we use
the setSearchTerm function elsewhere in our application, and
the local storage is not updated.
=> We’ll use React’s useEffect Hook to trigger the side-effect
each time the searchTerm changes.
React's useEffect Hook takes two arguments.
The first is a function that runs the side-effect. In this case, the
side-effect stores the searchTerm into the browser's local storage.
The function for the side-effect is called every time the
searchTerm changes and initially when the component renders
for the first time.
The second argument is a dependency array of variables.
Leaving out the second argument would make the function for the side-effect run on every render.
If the dependency array is an empty array, the function for the side-effect is only called once after the
component renders for the first time.
The useEffect Hook lets us opt into React's component lifecycle.
It can be triggered when the component is first mounted, but also if one of its dependencies is updated.
Improving Reusability of the Search Component
The Search component is tightly tied to search feature
- Makes it less reusable for other tasks needing same label & input field
- risks introducing bugs if two are rendered side by side with same htmlFor/id combination
+ Solution: make Search component reusable by generalizing domain-specific properties
Pass dynamic id and label prop to make component reusable for other tasks
Rename value and callback handler to something generic
Rename the component accordingly after making changes for reusability
7
▪ If input field needs to have a specific data type (e.g. number,
phone number)
➔ the type attribute of the input field needs to be accessible
from the outside.
▪ If type prop is not passed from App to InputWithLabel:
- Default parameter from function signature takes over for type,
- Default type is text if type prop not used
Changes made to improve reusability:
- Generalized naming of internal implementation details
- Increased API surface to provide necessary information from
outside
Component now has increased ability to handle tasks if used
elsewhere

Component composition in React


Discover how to use a React element as an HTML In the InputWithLabel component, you have access
element, with an opening and closing tag: to this label information through React's children
Instead of using the label prop from before, we prop. Instead of using the label prop, use the
inserted the text “Search:” between the children prop to render everything that has been
component’s element’s tags. passed down.

Now the React component’s elements behave similar to native HTML. Everything that’s passed between a
component’s elements can be accessed as children in the component and be rendered somewhere.
Sometimes when using a React component, you want to have more freedom from the outside what to render
in the inside of a component:
With this React feature, we can compose React components into each other. We’ve used it with a JavaScript
string and with a string wrapped in an HTML element. ( <strong> Search </strong> )

Inline Handler in JSX


The list of stories we have so far is only an unstateful
variable. We can filter the rendered list with the search
feature, but the list itself stays intact if we remove the
filter. The filter is just a temporary change through a
third party (searchTerm), but we can’t manipulate
the real list yet. To gain control over it, make it
stateful by using it as initial state in React’s useState
Hook. The returned values are the current state
(stories) and the state updater function (setStories).
Using this Hook enables us to manipulate the list
directly and update it based on user input.
8

The application behaves the same because the stories, now returned from useState, are still filtered into
searchedStories and displayed in the List. Next we’ll manipulate the list by removing an item from it:

The callback handler in the App


component receives an item to be
removed as an argument, and
filters the current stories based on
this information by removing all
items that don’t meet its
condition(s). The returned stories
are then set as new state, and the
List component passes the
function to its child component.
It’s not using this new
information; it’s just passing it on:

Add button element


Item component uses the incoming callback handler as a function in a new handler. In this handler, we will
pass the specific item to it. Moreover, an additional button element is needed to trigger the actual event.
9

Promise Function
Promise is an object that represents a value that may not be available yet but will be resolved at some point in
the future.
Promises are commonly used in asynchronous
programming to avoid callback hell
Promises have three states:
• pending: initial state, neither fulfilled nor rejected.
• fulfilled: the operation was completed successfully.
• rejected: meaning that the operation failed

 Promises provide a more readable way of dealing with asynchronous programming in JavaScript
 Promises can be resolved or rejected using the resolve and reject functions
 Promises can be chained using the then method and errors can be handled using the catch method
React Asynchronous Data
We have two interactions in our application: searching the list, and removing items from the list. The first
interaction is a fluctuant interference through a third-party state (searchTerm) applied on the list; the second
interaction is a non-reversible deletion of an item from the list.
Sometimes we must render a component before we can fetch data from a third-party API and display it.
In the following, we will simulate this kind of asynchronous data in the application. In a live application, this
asynchronous data gets fetched from a real remote API. We start off with a function that returns a promise –
data, once it resolves – in its shorthand version. The resolved object holds the previous list of stories.

In the App component, instead of using the initialStories, use an empty array for the initial state. We want to
start off with an empty list of stories, and simulate fetching these stories asynchronously. In a new useEffect
hook, call the function and resolve the returned promise. Due to the empty dependency array, the side-effect
only runs once the component renders for the first time:
10

Even though the data should arrive asynchronously when we start the application, it appears to arrive
synchronously, because it’s rendered immediately. Let’s change this by giving it a bit of a realistic delay,
because every network request to an API would come with a delay. First, remove the shorthand version for
the promise:

 After starting the app again, there is a delayed rendering of the list Initial state for stories is an
empty array. Side-effect hook runs once to fetch asynchronous data after App component is rendered.
After resolving promise and setting data in state, component renders again and dislay list of asynchronously
loaded stories.
React Conditional Rendering
Conditional rendering happens when different JSX is rendered based on state or props.
Asynchronous data is a good use case for dealing with these conditional states.
Example: initializing an application with no data, loading data, and displaying it once available.
Error handling is also important for handling failed data fetching.
Conditional rendering is a powerful tool in React for handling asynchronous data and error handling
Handling Loading Indicators in React
Some cases are already handled in React, like an empty list instead of null. However, other cases like loading
indicators still need to be implemented.
A loading indicator can provide users with feedback about pending data requests. To implement it, create a
new state for the indicator. Use this state to conditionally render the loading indicator while the data is being
fetched.
=> Implementing a loading indicator is essential for providing a better user experience in React application
With JavaScript’s ternary operator, we can inline this conditional state as a conditional rendering in JSX:

JavaScript’s ternary operator


The conditional (ternary) operator is the only JavaScript operator
that takes three operands:
• A condition followed by a question mark (?)
• An expression to execute if the condition is truthy followed by a colon (:)
• The expression to execute if the condition is falsy.
This operator is frequently used as an alternative to an if...else statement.
11

Error Handling in React for Asynchronous

Data Asynchronous data fetching can have


errors, which need to be handled in React.
Introduce a new state for error handling in React.
Handle the error in the promise's catch()
block when resolving the promise. This will
update the error state, allowing you to
conditionally render an error message to
the user.
Error handling is crucial in React applications
when dealing with asynchronous data.
It's important to handle errors properly to
provide a better user experience.

Logical AND Operator in JavaScript and React


In React, we can use this behaviour for conditional rendering.
If the condition is true, the expression after the logical
&& operator will be the output. (true && 'Hello World' always
evaluates to 'Hello World') If the condition is false, React
ignores it and skips the expression. (false && 'Hello World'
always evaluates to false)

Next, give the user feedback in case something went wrong


with another conditional rendering. This time, it’s either
rendering something or nothing. So instead of having a
ternary operator where one side returns null, use the
logical && operator as shorthand:

Conditional Rendering in React for UI Dynamism


Conditional rendering is not just for asynchronous data; it can also be used with boolean flags. With a boolean
flag, you can toggle the rendering of JSX based on the flag's value.
Conditional rendering is a powerful tool in React for making your UI more dynamic. It is necessary for more
complex control flows like asynchronous data.
Data Fetching with React
We are currently fetching data, but it’s still pseudo data
coming from a promise we set up ourselves. The lessons
up to now about asynchronous React and advanced state
management were preparing us to fetch data from a real
third-party API. We will use the reliable and informative
Hacker News API to request popular tech stories.
JavaScript’s Template Literals for a string interpolation.
When this feature wasn’t available in JavaScript, we’d have used the + operator on strings instead

The API_ENDPOINT is used to fetch popular tech stories for a certain query (a search term).
The native browser’s fetch API is used to make this request.
For the fetch API, the response needs to be translated into JSON. The returned result is used to set the list of
stories (setStories)
12

Moving Search Feature to Server-Side


- App component fetches a list of stories with a predefined query (React).
- Users can search for stories on the client-side.
- Moving search feature to server-side searching.
- Using the searchTerm as a dynamic query for the API request.
Benefits: • Faster search results • Reduced network traffic • More secure search functionality
Remove searchedStories because we will receive the stories searched from the API. Pass only the regular
stories to the List component
Instead of using a hardcoded search term like If the searchTerm changes however, we need to run the side-
before, use the actual searchTerm from the effect for the data fetching again.
component’s state. In addition, if searchTerm is not present (e.g. null, empty
If searchTerm is an empty string, do nothing string, undefined), do nothing (as a more generalized
condition):

From Client-Side to Server-Side Search


Changed feature from client-side to server-side search.
SearchTerm is used to fetch a server-side filtered list.
Server-side search happens for initial data fetching and subsequent data fetching when searchTerm changes.
Re-fetching data each time someone types into input field isn't optimal so we need to optimize the
implementation. API may experience errors due to excessive requests.
Explicit Data (Re-)Fetching
Third-party API internals are out of our reach. Eventually, we will incur rate
limiting, which returns an error instead of data. We will have to change
implementation from implicit to explicit data (re-)fetching: refetch data only
if someone clicks a confirmation button.
Benefits: • Reduces rate limiting errors • Optimizes performance
• Provides a better user experience
We will add a button element for the confirmation to the JSX
The handler, input, and button handler receive implementation logic to update
the component’s state.
The input field handler still updates the searchTerm;
The button handler sets the url derived from the current searchTerm and the
static API URL as a new state:
Instead of running the data fetching side-effect on every searchTerm change
– which would happen each time the input field’s value changes – the url is used.
The url is set explicitly by the user when the search is confirmed via our button
Refactoring the SearchTerm
SearchTerm previously used for updating input
field's state and activating the side-effect for
fetching data.
Considered too many responsibilities for the
searchTerm.
SearchTerm now only used for updating input
field's state.
Introduction of a second state called URL for
triggering side-effect for fetching data.
Data fetching only happens when a user clicks the
confirmation button

You might also like