I don’t remember when I had first contact with React… and when I lost myself to this library. However, I didn’t use it much with commercial projects as most of the big tech companies go more towards Angular. After a few years of working mostly in Angular, I just finished my third commercial project in React and it’s truly awesome.
So where does this library work best, what exactly is it, and how do you start your journey with React? Well, let me paraphrase Morpheus’ words:
“You take the blue pill, the story ends, you wake up in your bed and believe whatever you want to believe. You take the red pill, you learn React, and I show you how deep the rabbit hole goes.”
First things first — what is React?
React is a library you can use to render sites. Unlike other popular JavaScript libraries, it performs one task only — renders the DOM — instead of trying to be a full framework with all the tools you need to create a single-page application. As a result, we get a small package that focuses exclusively on rendering, not providing users much else. Later in the article, we will discuss the pros and cons of this kind of approach.
It’s all about the logic
JSX syntax
JSX is a special syntax that allows us to transpile HTML markups into a value of the function. We’re getting site content along with business logic in one file.
const element = () => <h1>Test</h1>
ReactDOM.render(element, document.getElementById('root'));
JSX variables
To render variables in React we need to wrap them in curly braces. Such code responds to potential changes in variable const name
const name = "React pill"
const element = <h1>{name}</h1>
ReactDOM.render(element, document.getElementById('root'));
Calling functions
Calling functions from a JSX element looks exactly like the variables example, using braces.
function joinName(user) {
return `${user.name} ${user.surname}`;
}
const user = { name: "Mateusz", surname: "Reszka" }
const element = <h1>{joinName(name)}</h1>
ReactDOM.render(element, document.getElementById('root'));
Rendering elements
React uses so-called virtual DOM and compares newly generated DOM with the previous one that's already saved in memory to find the differences between the two. This way it tries to optimize the operations and avoid unnecessary changes directly on the DOM.
Clear and simple components
React's structure allows the preparation of small components, which might help with the readability of larger components or even pages.
const ButtonComponent = (props) => <button
class={props.color}
type={props.type}
onClick={props.onClick}>
{name}
</button>
Managing the state and life cycle
State
Every big app needs to store its state. React allows us to apply two different approaches to managing the state:
- using the classes (inherited from React.Component state value )
- using a so-called hook API, for example using hook useState.
Although both approaches are supported, the second one was implemented recently and is currently the focus of most maintenance work.
// Managing the state (class)
class Clock extends React.Component {
constructor(props) {
super(props);
this.state({date: new Date()});
}
render() {
<div>{this.state.date}</div>
}
}
// Managing the state (function)
const Clock = (props) => {
const [state, setState] = useState({date: new Date()});
return (
<div>{state.date}</div>
)
}
Lifecycle
In order to perform the operation after rendering or removing elements from DOM, we use lifecycle hooks. Again, there are two different ways of using React to render components. The choice depends on using class in function or function.
// Life cycle (class)
// happens right after initial rendering
componentDidMount() {}
// happens right before removing from DOM
componentWillUnmount() {}
// Life cycle (function)
useEffect(() => {
// happens after initial render
// and every time dependency array gets changed
return () => {
//happens right before removing from DOM
}
}, [] //dependency array
);
Events in React
Sooner or later every application and every form needs to contact with backend, redirect the user to another site or respond to the user's activity. Events in React are not much different than those we can find in HTML5 specs. The exception to this is that they use camelCase. Below is a simple example of how to use HTML5 onclick event:
const handleSubmit = (event) => {
console.log('trigger!');
}
<button onClick={handleEvent}>Submit</button>
Here, in turn, is an example of how to use ‘onsubmit’. PrevendDefault acts identically like in HTML5 - allows preventing the default page reload to the form’s submit.
function Form() {
function handleSubmit(e) {
e.preventDefault();
console.log('You clicked submit.');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
Conditional rendering
React allows us to render completely different elements depending on function/class business logic. That way we can stop running further logic very early, by rendering alternative content. The below example shows how Condition's component returns error and stops further code execution when the variable error is set to true.
function Condition({error = false}) {
if (error)
return <>Error!</>
return <>No error</>
}
Required lists and keys
Lists and all the .map expressions are running during the runtime. The consequence is that every .map call causes re-render of the whole collection of items. To make it more efficient (and to avoid re-rendering) React requires a key parameter, which informs whether there is a need to render a part or a whole collection. It is important that the 'key' be unique in the whole collection.
function ListItems = () => {
const entries = [ 'orange', 'apple']
return <div>
<ul>
{
entries.map((item, index) => (
<li>}{item.API} - {item.Description}</li>
))
}
</ul>
</div>
}
A handful of conclusions and advice
React is a small but powerful library and breaking changes appear very rarely. Upgrades aren't causing problems very often like what tends to happen in Angular. Unfortunately, this approach means that there are a lot of missing features you need to write on your own (i.e. form validation which is a built-in Angular feature) or you need to rely on other libraries.
React works great in small and medium-sized projects. As an example, there is a case study of the project based on NFT in which we used this library. In bigger commercial applications using React could be challenging and require a little more discipline and frequent code refactoring.
Worth checking out - additional content on reactjs.org
So that's roughly what the entrance to the rabbit hole looks like. Now, I wish you a productive time exploring it!