React is a powerful and flexible JavaScript framework used to create user interfaces quickly. Just like any other frameworks, React has it's own ways of doing things. In this lesson, we are going to go over all the rules you must follow in order to create high quality React applications.
Components must be pure during render
One of the most important principle in React is that components should be pure functions, meaning when provided with the same input arguments, they should always return the same response, and contains no side effects.
By making your components pure, the app becomes predictable and easier to debug, and allows React to optimize them correctly.
As an example, the following component is not pure:
1function RandomNumber() {
2 return <span>{Math.random()}</span>;
3}
Because Math.random()
will generate a different number every time it is called, causing RandomNumber()
to return a different value on every render.
The following example is also not pure. This example is intended to retrieve a random quote from an API, and then display that quote. Because retrieving data from a remote source is a side effect, it makes this component not pure. If the remote data changes, the component will render differently.
1import { useState } from "react";
2
3function RandomQuote() {
4 const [quote, setQuote] = useState("");
5
6 async function fetchQuote() {
7 const response = await fetch("https://api.quotable.io/random");
8 const data = await response.json();
9 setQuote(data.content);
10 }
11
12 fetchQuote();
13
14 return <div>{quote ? quote : "Loading..."}</div>;
15}
16
17export default RandomQuote;