Introduction to react js
ReactJS is a powerful JavaScript library used to build modern web applications. It is fast, efficient and easy to use. ReactJS enables developers to create dynamic user interfaces with its declarative components, hooks and lifecycle methods.
With react, developers can easily manage the state of their applications using the useState
hook and the useEffect
hook allows them to perform side effects in their components. The useRef
hook makes it easy for developers to access DOM nodes in their application for better control over performance.
Reactjs is an essential tool for modern web development as it has a huge ecosystem of libraries, tools and resources that help developers create amazing user experiences quickly and efficiently. It is developed and maintained by Facebook, and it provides developers with tools to create powerful web applications with the help of the components they write.
How does React Work?
Instead of directly altering the DOM, React builds a shadow version of it in memory, where it makes all its edits. Only after this process is completed does it then apply the changes to the browser's DOM. This helps optimize performance and keeps our code cleaner. React finds out what changes have been made, and changes only what needs to be changed.
Main Features of ReactJS
Some of the main features of React include:
Components: React allows developers to build applications using reusable components, making it easier to maintain and scale the code.
Virtual DOM: React uses a virtual DOM, which optimizes updates and rendering of components, resulting in improved performance.
One-Way Data Flow: React follows a one-way data flow, also known as unidirectional data flow, which helps to prevent any potential conflicts in the application and makes it easier to understand how the data is being updated and managed.
JSX: React uses JSX, a syntax extension for JavaScript, which allows developers to write HTML-like code within JavaScript, making it easier to understand and write code.
Server-side Rendering: React allows for server-side rendering, which can improve the initial loading speed of an application and provide a better experience for users.
Flexibility: React is flexible and can be used with a variety of programming languages and tools, making it easy to integrate into an existing technology stack.
Strong Community Support: React has a large and active community of developers, which provides a wealth of resources, including libraries, tools, and support.
These are some of the main features of React that make it a popular choice for building user interfaces.
How to Use React
There are two ways to use react
Write React directly to HTML
Setting up a React Environment
Write React directly to HTML
To kickstart your React learning journey, the best approach is to directly incorporate it into HTML files. This is the fastest route to start writing in React.
To get started, add three scripts to your project: the first two will let you write React code in JavaScript files, while the third script (Babel) enables you to use JSX syntax and ES6 features for older browser compatibility. Like in the example code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="mydiv"></div>
<script type="text/babel">
function Hello() {
return <h1>Hello World!</h1>;
}
ReactDOM.render(<Hello />, document.getElementById('mydiv'))
</script>
</body>
</html>
This method of using React is not recommended especially if it's being created for production, consequently, setting up react environment is much better.
Setting up a React Environment
To set up react environment, one has to ensure that npx and node.js are installed. Also, depending on the package manager you are using (i.e whether npm or yarn), you can use the appropriate installation command for the package manager but we will be using yarn here.
Run this command to create a React application named first-react-app
:
yarn create react-app first-react-app
The create react-app
will set up everything you need to run a React application.
To start or run the react application, we will have to navigate to our react folder first-react-app
then we run this command yarn start
to start our react app.
A new browser window will pop up with your newly created React App! If not, we can open our browser and type localhost:3000
in the address bar or any other port given to you.
Modifying the React Application
We can decide to change the contents of the react app. If we look in the first-react-app
directory and will find folders like src
public
folder. Inside these folders, we can decide to edit or delete the contents of the files in the folder to fit what we want.
Here is what a file called App.js
looks like when you first open it.
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
But we can decide to change or trim its content to look like below
function App() {
return (
<div className="App">
<h1>Hello World!</h1>
</div>
);
}
export default App;
The part of React that makes sense to me: the part of react that I find very interesting
React useEffect
Hooks
The useEffect
Hook is a great way of incorporating side effects into React components.
These can take many forms, such as fetching data, changing the DOM and setting timers. The function that it takes in as an argument uses two parameters, of which the second one is optional.
The syntax follows useEffect(<function>, <dependency>)
3 ways to use useEffect
1. No dependency passed:
useEffect(() => {
//Runs on every render
});
2. An empty array:
useEffect(() => {
//Runs only on the first render
}, []);
3. Props or state values:
useEffect(() => {
//Runs on the first render
//And any time any dependency value changes
}, [prop, state]);
Example:
Here is an example of a useEffect
that only runs on the initial render:
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
}, []); // <- add empty brackets here
return <h1>I've rendered {count} times!</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);
Output:
Conclusion
To prevent memory leaks, it's important to take care of any leftover effects like timeouts, subscriptions, event listeners etc. We can do this by including a return statement at the end of the useEffect
hook. This helps clean up those unwanted effects and ensure efficient memory usage.