Facebook created React in 2013 as an alternative to AngularJS, the prominent JavaScript framework at the time. To better suit the requirements of Facebook’s server-side rendering, React was made very different from Angular. For instance, React is a dynamic library while Angular is a restrictive framework. React supports flexible TypeScript, but Angular supports only static TypeScript. Such differentiations led to the development of web frameworks by leaps and bounds.
Today, React is the second most popular JavaScript framework in the world. If you are getting started with this JS framework, it might seem overwhelming. However, our engineers created this React cheat sheet to give you an overview of some important React features in simple-to-understand snippets.
1. JSX
JSX is short or JavaScript XML which is a syntax extension of JavaScript to write HTML code.
It will be a bit complicated if you have to write HTML in React without JSX. Here’s an example:
const myelement = React.createElement(‘h1’, {}, ‘Hello World!’);
ReactDOM.render(myelement, document.getElementById(‘root’));
The same code can be restructured like this using JSX:
const myelement = <h1>Hello World!</h1>;
ReactDOM.render(myelement, document.getElementById(‘root’));
Evidently, JSX makes it a lot easier and faster to write HTML elements in React code. In its absence, you will be forced to use the ReactDOM.render() function, which takes two arguments – the HTML code and the HTML element to render the code.
Here’s an extensive JSX cheat sheet that React developers must check out.
2. React fragments
In React, it is required that all returned elements must be returned within a “parent” component. For example, consider the following code:
function MyComponent() {
return (
<h1>My header</h1>
</p>My paragraph</p>
);
}
It is an invalid React code because here, two sibling elements, H1, and a paragraph, are returned from the same component.
React has an element called a fragment. They are the components that allow wrapping or grouping multiple elements without adding an extra node to the DOM.
If you want to overcome this limitation, you can use a fragment.
// valid syntax
function MyComponent() {
return (
<>
<h1>My header</h1>
</p>My paragraph</p>
</>
);
}
Here we did not wrap our elements in any container element like a DIV, instead used a fragment. The syntax for using React fragments is:
<React.Fragment>
.
.
.
</React.Fragment>
or
<>
.
.
.
</>.
3. React conditionals
All React components and elements are displayed conditionally. A basic approach to creating a separate return is using an if-statement like this:
function App() {
const isAuthUser = useAuth();
if (isAuthUser) {
// if our user is authenticated, let them use the app
return <AuthApp />;
}
// if user is not authenticated, show a different screen
return <UnAuthApp />;
}
React codes using if-statement can be highly nested. It is possible to write a conditional within a return statement. It simplified the React code like this:
function App() {
const isAuthUser = useAuth();
return (
<>
<h1>My App</h1>
{isAuthUser ? <AuthApp /> : <UnAuthApp />}
</>
)
}
You must wrap the entire conditional in curly braces. Also, a conditional must resolve to a value.
4. React context
You can use context to pass data to the React components tree without using props. The problem with props is that we are sometimes forced to pass them through components that don’t need them in React codes. This is known as props drilling.
In the snippet below, the props are passed through a Body component that doesn’t need it:
function App() {
return (
<Body name=”John Doe” />
);
}
function Body({ name }) {
return (
<Greeting name={name} />
);
}
function Greeting({ name }) {
return <h1>Welcome, {name}</h1>;
}
To overcome this issue, we use the createContext function from React.
You can call context with an initial value. A createContext function has two components – a Provider and a Consumer property. The Provider is wrapped around the component tree through which the given value is to be passed. Next, you place the Consumer in the component from which you want to consume the value.
Example code:
import { createContext } from ‘react’;
const NameContext = createContext(”);
function App() {
return (
<NameContext.Provider value=”John Doe”>
<Body />
<NameContext.Provider>
);
}
function Body() {
return <Greeting />;
}
function Greeting() {
return (
<NameContext.Consumer>
{name => <h1>Welcome, {name}</h1>}
</NameContext.Consumer>
);
}
However, before you use the context to optimize the React code, see if you can better organize the components to avoid passing props through components that don’t require it.
5. React useState hook
Hooks were introduced in React version 16.8 and completely overhauled React’s use. They allow adding reusable, stateful logic to React function components.
One important React hook is useState. It does what it says; it allows React developers to use stateful values in function components.
The useState hook is preferable over a simple variable because when the component’s state is updated, it can display the updated value.
Here’s an example of using useState to increment a counter:
import { useState } from ‘react’;
function MyComponent() {
const [stateValue, setStateValue] = useState(initialValue);
}
We can identify the current count from the count variable and can increment the state by passing count + 1 to the setCount function like this:
import { useState } from ‘react’;
function Counter() {
const [count, setCount] = useState(0);
function updateCount() {
setCount(count + 1);
}
return <button onClick={updateCount}>Count is: {count}</button>;
}
Conclusion
Even though it is fairly concise, this React cheat sheet covers the five most important features of the JavaScript framework that beginners should learn. As you practice and grow, you will discover many more features. Don’t be intimidated or overwhelmed; just start writing code.
React developers can explore job opportunities with Talent500. We are a trusted partner of some of the largest tech companies to build their engineering teams. Join our elite pool of talent.
Add comment