How React flirts with data
Olatunde Adedeji
Posted on July 22, 2022
React is the Rolls Royce of frontend development inspiring greatness in designing user interfaces. Undoubtedly, React is a JavaScript library for building user interfaces. React focuses explicitly on building UI for web and mobile applications. React is so popular, flexible, and declarative- the React API does the heavy lifting for you in building user interfaces. React allows you to develop reusable components that are easy to read, scale and maintain.
Essentially, React component consists of a markup mix of HTML, styled by CSS, and with smooth interactivity handled with the help of JavaScript.
React has a large community of developers who are ready to help you all the way in learning and understanding the intricacies of React ecosystem. The die-hard React fans would tell you this is the best time to be a web developer- the wholesome developer experience is eccentric with a great feeling of nothing is impossible with user interface coding!
However, in this article, we are going to learn how React handles data we use in web applications. Data is critical to every web application and React does excellently well in handling data, data in the component state, passing data from one component to another, and fetching data from an API data source. We will explore in specific how React handles data fetching using Fetch API.
Understanding data and its uni-directional flow
Conventionally, data flows in one-way directional movement in React. It means there is only one source that the rest of your application components expect data to come from and that source is a parent component, nowhere else. Technically, in React, data flows from the parent component to the child component. This flow is in form of props. Props are the carrier of component information. Data is not expected to flow from child to parent or child to child. This encourages a definite single source of truth for data. Why would React enforce the uni-directional flow of data?
The reasons are not far-fetched:
It is easier to debug, as we know where data is coming from.
Unidirectional data flow is less prone to errors, as we have more control over our data.
It is more efficient, as the library knows what the boundaries are of each part of the disparate system.
Data in the database
Hardly will you see a web application without a backend service. Of course there are many benefits of keeping your data in a database. Firstly, data persistence improves user experience. Users of your web application will appreciate a system that makes storage and retrieval of data- users information a painless adventure. React shines with its controlled component form ability in capturing user inputs and relaying it back when needed with little or no latency.
Secondly, we need to consider data security and how React rises to occasion. Data security starts from the point of data collection. Are users able to submit HTML contents to your backend service? If yes, are you using React best practices to ensure the right data in the right form get to your database? No developer is ever proud of a system vulnerable to SQL injection. SQL injection describes a scenario a playful or bad actor user exploit the vulnerability of your web applications in injecting exploitative SQL codes in your system that is capable at the extreme case, of CRUD operations. Nobody wants this but you have to expect it and be defensive against SQL injection attacks in your development.
Imagine this gets to execute on your database from your form input fields:
DROP TABLE IF EXISTS dbo.Customers;
It will definitely be embarrassing!
So, handling dangerous form data before the son of a bitch gets to your database is ever more important to retain your job as a developer and to maintain the good credibility of your company or clients. User data sanitization is critical and for React applications, an open source package such as Formik helps reduce the burden of form development. You can even go the extra mile with what the package has to offer to be at the safer end of what goes into your database.
Concept of immutability
Immutability makes data flow easier to understand in React applications. An immutable variable means its value cannot change after being created. Mutability and immutability are frequently used in programming in a rather confusing or probably complex way.
Why are we not using simple terms like can change, modifiable (mutable) or cannot change, not modifiable (immutable)?
These are rather easier to understand anyway this is by the way! Developers' communities are built around folks that love complex words- we are all in it together!
Technically, JavaScript Strings value types are immutable. You can’t directly change its value but you can re-assign it to another value.
var strings =”John Joel”;
You can’t do this:
strings[3] =”p”;
You can only mutate string values with some methods like replace(), trim() etc
React says do not mutate(change) the state property of a component directly. In essence, state values are immutable. But with a caveat, you can only change the state value with a function updater method- setState(). This help instils some sanity into the coding culture and makes debugging easier.
React unequivocally says, how you handle your data is up to you, even mutations. In large React applications, performance tends to be a major reason why we care so much about how data mutate. A change in states naturally can cause React components to re-render. You wouldn't want expensive re-rending to impair the performance of your React applications. In redux, a way to manage complex state data in React. You deal with state mutations through reducers not directly. So, immutability in React encourages a single source of truth of your data. You also tend to have cleaner codes with clarity of your functions' behaviour.
Fetching data from an external data source
Dealing with external data sources in React could be a no-brainer with the right approach. We are going to see how fetching data is loaded into React from an external source using a simple fetch().
Why fetch()? It is native to our browsers. It is right there on the window object- window.fetch. No need of extra package installation. You simply hit the ground running with your Http request handling in a promise based request approach.
Let's make a simple GET request with fetch(). And all we have to do is to include the URL endpoint to which we want to make our request in the Fetch() method.
import React, { useState, useEffect } from 'react';
const App=()=> {
const [people, setPeople] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// GET request using fetch with useEffect Hook
setIsLoading(true);
fetch('https://swapi.dev/api/people/')
.then(response => response.json())
.then(data => setPeople(data.results));
setIsLoading(false);
// Empty dependency array means this effect will only run once
}, []);
return (
<div>
<h5>Get Data from an API Data Source</h5>
{isLoading? <p>Loading people...</p>: people.map(person => <p key={person.name}>{person.name},{person.mass}, {person.height}</p>)} <div>
{}
</div>
</div>
);
}
export default App;
Let’s quickly break the code down:
We import useState and useEffect Hooks to bring them to scope in our applications.
The const [people, setPeople] = useState([]) and the const [isLoading, setIsLoading] = useState(true) were set to manage people and isLoading states
We then have useEffect to handle the logic of data fetching from the endpoint
The endpoint URL was passed as parameter to fetch('https://swapi.dev/api/people/')
The .then() callback returns a new promise with the conversion of response to a JSON data
The second .then() callback assign the JSON response data to our state variable-people
We then call on the map() to iterate on the arrays of people objects returned.
In conclusion,
We can see that React shines well among peers in handling data in any web application of any size and complexity. Its uni-directional data flow enables developers to understand where data is coming from and what it is capable of becoming, thus makes debugging easier.
The immutability concepts in React applications optimizes complex applications for better performance. You then ensure you are developing pure components with predictable behaviour since you know how your variables, arrays and objects might behave.
Finally, the understanding of React ability to flirt with data will not be complete without making refence to how React handles data from a data source, a daily application development task for every professional developer. React library for building user interface handle data with a touch of class.
Posted on July 22, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 2, 2024