Cryptocurrencies have become increasingly popular in recent years, and the need for reliable and efficient tracking tools has never been greater. In this article, we will explore how to create a cryptocurrency tracker using React and Redux. React is a popular front-end library for building user interfaces, and Redux is a predictable state container for managing application state. By the end of this article, you will have a solid understanding of how to create a cryptocurrency tracker with React and Redux.
Understanding React and Redux
Before we dive into the details of creating a cryptocurrency tracker, it’s important to understand what React and Redux are and how they work together.
What is React?
React is a JavaScript library for building user interfaces. It was created by Facebook and is widely used in web development. React allows developers to create reusable UI components, making it easier to build and maintain complex user interfaces. React uses a declarative syntax, which means developers describe what they want to happen, and React takes care of the details.
What is Redux?
Redux is a predictable state container for JavaScript applications. It was inspired by Flux, another state management library, and is commonly used with React. Redux helps manage the state of an application in a predictable and scalable way. Redux provides a centralized store for application state and allows for actions to be dispatched, which then trigger updates to the state.
Why use React and Redux together?
React and Redux work well together because they both prioritize declarative code and share similar principles. React provides the view layer, while Redux provides the state management layer. Together, they create a predictable and efficient way to manage application state and update the UI.
Building a Cryptocurrency Tracker with React and Redux
Now that we have a basic understanding of React and Redux, let’s dive into building a cryptocurrency tracker. We will use the CoinGecko API to retrieve real-time cryptocurrency data.
Step 1: Setting up the project
The first step is to set up the project. We will use Create React App to create a new React project. Open your terminal and run the following command:
npx create-react-app crypto-tracker
This will create a new React project called “crypto-tracker” in your current directory. Next, navigate to the project directory and install the necessary dependencies:
cd crypto-tracker npm install --save redux react-redux axios
We will be using Redux to manage the state of the application, react-redux to connect our React components to the Redux store, and axios to make API requests.
Step 2: Creating the Redux Store
Next, we need to set up the Redux store. Create a new file called “store.js” in the “src” directory and add the following code:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
This creates a new Redux store with the “rootReducer” and applies the “thunk” middleware. We will be using thunk to handle asynchronous actions.
Step 3: Creating the Reducers
Now that we have our store set up, we need to create the reducers. Create a new directory called “reducers” in the “src” directory and create a new file called “cryptoReducer.js”. Add the following code:
import { GET_CRYPTO } from '../actions/types';
const initialState = {
cryptoData: []
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_CRYPTO:
return {
...state,
cryptoData: action.payload
};
default:
return state;
}
}
This creates a new reducer called “cryptoReducer” that handles the “GET_CRYPTO” action. The initial state of the reducer is an empty array, which will be populated with cryptocurrency data when the action is dispatched.
Step 4: Creating the Actions
Next, we need to create the actions. Create a new directory called “actions” in the “src” directory and create a new file called “cryptoActions.js”. Add the following code:
import axios from 'axios';
import { GET_CRYPTO } from './types';
export const getCrypto = () => async dispatch => {
try {
const res = await axios.get('https://api.coingecko.com/api/v3/coins/markets? vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false');
dispatch({
type: GET_CRYPTO,
payload: res.data
});
} catch (error) {
console.log(error);
}
};
This creates a new action called “getCrypto” that retrieves cryptocurrency data from the CoinGecko API and dispatches the “GET_CRYPTO” action with the retrieved data as the payload.
Step 5: Creating the Components
Now that we have the store, reducers, and actions set up, we can create the React components.
Create a new file called “CryptoList.js” in the “src/components” directory and add the following code:
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getCrypto } from '../actions/cryptoActions';
const CryptoList = () => {
const dispatch = useDispatch();
const cryptoData = useSelector(state => state.cryptoReducer.cryptoData);
useEffect(() => {
dispatch(getCrypto());
}, [dispatch]);
return (
<div>
<h1>Cryptocurrency Tracker</h1>
<table>
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Price</th>
<th>24h Change</th>
<th>Market Cap</th>
</tr>
</thead>
<tbody>
{cryptoData.map(crypto => (
<tr key={crypto.id}>
<td>{crypto.market_cap_rank}</td>
<td>{crypto.name}</td>
<td>${crypto.current_price}</td>
<td>{crypto.price_change_percentage_24h}%</td>
<td>${crypto.market_cap.toLocaleString()}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default CryptoList;
This creates a new component called “CryptoList” that retrieves cryptocurrency data from the Redux store using the “useSelector” hook and dispatches the “getCrypto” action using the “useEffect” hook. The component then displays the cryptocurrency data in a table.
Step 6: Rendering the App
Finally, we need to render the app. Open the “src/index.js” file and replace the existing code with the following:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import CryptoList from './components/CryptoList';
ReactDOM.render(
<Provider store={store}>
<CryptoList />
</Provider>,
document.getElementById('root')
);
This renders the “CryptoList” component and provides it with access to the Redux store using the “Provider” component.
In this article, we learned how to create a cryptocurrency tracker using React and Redux. We used the CoinGecko API to retrieve real-time cryptocurrency data and created a React component to display the data in a table. By using Redux, we were able to manage the state of the application in a predictable and efficient way. This example demonstrates the power of React and Redux in creating efficient and scalable web applications.