React
React
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.
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
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.
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:
OR
5
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> )
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:
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:
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