Building a Simple CRUD Application with React and Redux
Creating a CRUD (Create, Read, Update, Delete) application is a fundamental exercise for any developer looking to master modern web development. In this article, we’ll walk through building a simple CRUD application using React and Redux. This will not only enhance your understanding of these powerful libraries but also give you hands-on experience in managing application state and user interactions.
What is CRUD?
CRUD stands for Create, Read, Update, and Delete. These four operations are the basic functions of persistent storage and are crucial for applications that handle data. A typical CRUD application allows users to perform these operations on items, such as tasks in a to-do list or records in a database.
Use Cases for CRUD Applications
- To-Do List Applications: Simple apps for task management.
- Inventory Management Systems: Keep track of products and stock levels.
- User Management: Create and manage user profiles in platforms.
- Blog Platforms: Allow users to create, read, update, and delete posts.
Setting Up the Project
Before we dive into coding, let’s set up our React project environment. You’ll need Node.js and npm installed on your machine.
- Create a new React application using Create React App:
bash
npx create-react-app crud-redux-app
cd crud-redux-app
- Install Redux and React-Redux:
bash
npm install redux react-redux
- Install additional dependencies for easier state management:
bash
npm install @reduxjs/toolkit
Structuring the Application
Here’s how we’ll structure our application:
/src
/components
AddItem.js
ItemList.js
/features
itemsSlice.js
/app
store.js
App.js
Creating the Redux Store
First, let's set up our Redux store in src/app/store.js
:
import { configureStore } from '@reduxjs/toolkit';
import itemsReducer from '../features/itemsSlice';
export const store = configureStore({
reducer: {
items: itemsReducer,
},
});
Defining the Items Slice
Next, create the items slice in src/features/itemsSlice.js
:
import { createSlice } from '@reduxjs/toolkit';
const itemsSlice = createSlice({
name: 'items',
initialState: [],
reducers: {
addItem: (state, action) => {
state.push(action.payload);
},
removeItem: (state, action) => {
return state.filter(item => item.id !== action.payload);
},
updateItem: (state, action) => {
const index = state.findIndex(item => item.id === action.payload.id);
if (index !== -1) {
state[index] = action.payload;
}
},
},
});
export const { addItem, removeItem, updateItem } = itemsSlice.actions;
export default itemsSlice.reducer;
Building Components
Now, let’s create our components.
1. AddItem Component
This component will allow users to add new items. Create src/components/AddItem.js
:
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addItem } from '../features/itemsSlice';
const AddItem = () => {
const [item, setItem] = useState('');
const dispatch = useDispatch();
const handleSubmit = e => {
e.preventDefault();
if (item) {
dispatch(addItem({ id: Date.now(), name: item }));
setItem('');
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={item}
onChange={e => setItem(e.target.value)}
placeholder="Add Item"
/>
<button type="submit">Add</button>
</form>
);
};
export default AddItem;
2. ItemList Component
This component will display the list of items. Create src/components/ItemList.js
:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { removeItem } from '../features/itemsSlice';
const ItemList = () => {
const items = useSelector(state => state.items);
const dispatch = useDispatch();
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name}
<button onClick={() => dispatch(removeItem(item.id))}>Delete</button>
</li>
))}
</ul>
);
};
export default ItemList;
Integrating Components in App.js
Now, let’s bring everything together in src/App.js
:
import React from 'react';
import { Provider } from 'react-redux';
import { store } from './app/store';
import AddItem from './components/AddItem';
import ItemList from './components/ItemList';
const App = () => {
return (
<Provider store={store}>
<div>
<h1>CRUD Application with React and Redux</h1>
<AddItem />
<ItemList />
</div>
</Provider>
);
};
export default App;
Running the Application
Now that everything is set up, you can run your application:
npm start
You should see your CRUD application where you can add items to the list and delete them as needed.
Troubleshooting Common Issues
- State Not Updating: Ensure your action creators and reducers are correctly defined.
- Component Not Rendering: Make sure you are using
Provider
fromreact-redux
and passing in the store. - Input Field Not Clearing: Check that you are resetting the state after dispatching the add action.
Conclusion
Building a CRUD application with React and Redux is an excellent way to get hands-on experience with state management and component architecture. By following the steps outlined in this article, you’ve not only created a functional application but also gained insights into the powerful capabilities of React and Redux.
Feel free to extend this application by adding features such as editing items or persisting data using local storage or a backend API. Happy coding!