React js redux tutorial
- Get link
- X
- Other Apps
React.js with Redux Tutorial: A Beginner's Guide
In this tutorial, we'll learn how to manage state in a React application using Redux. Redux is a predictable state container that helps you manage and maintain the state of your application in a predictable manner. Redux is especially useful for larger applications where you need to manage global state, and it works very well with React.
We’ll walk through the core concepts of Redux and how to set it up in a React project with practical examples.
Prerequisites
- Basic understanding of React.js (functional components, hooks, JSX, props, and state).
- Basic knowledge of JavaScript (ES6+ syntax).
- Familiarity with npm (Node Package Manager).
If you're new to React or Redux, feel free to go over some React basics before starting.
Step 1: Setting up the React Application
Create a new React app using Create React App (CRA) CLI tool:
bashnpx create-react-app react-redux-tutorial cd react-redux-tutorialInstall Redux and React-Redux (the official Redux bindings for React):
bashnpm install redux react-redux- redux: The core library for state management.
- react-redux: The binding library that connects Redux to React.
Step 2: Understanding Redux Core Concepts
Before we dive into the code, let’s briefly review the core concepts of Redux:
- Store: A central place where the entire state of the application lives.
- Actions: Plain JavaScript objects that describe "what happened" in the application (e.g., user interactions or network requests).
- Reducers: Functions that specify how the state of the application changes in response to an action.
- Dispatch: A function used to send an action to the Redux store.
- Selectors: Functions that allow you to extract or "select" a piece of the state.
Step 3: Create Redux Store, Actions, and Reducers
We’ll create a simple counter app as an example where we can increment and decrement a value using Redux.
1. Create Actions
Inside the src folder, create a new folder named redux, and inside it create an actions.js file:
js// src/redux/actions.js
export const increment = () => {
return {
type: 'INCREMENT'
};
};
export const decrement = () => {
return {
type: 'DECREMENT'
};
};
- These are action creators that return action objects. Each action object has a
typeproperty that describes the action (e.g., increment or decrement).
2. Create Reducers
Next, create a reducers.js file inside the redux folder:
js// src/redux/reducers.js
const initialState = {
count: 0
};
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
};
export default counterReducer;
- Reducers handle actions and update the state accordingly. In this case, we have a counter reducer that updates the
countstate based on the action type.
3. Create the Redux Store
Now, we need to create the Redux store that combines the reducers and initializes the app's state. Create a store.js file:
js// src/redux/store.js
import { createStore } from 'redux';
import counterReducer from './reducers';
const store = createStore(counterReducer);
export default store;
createStoreis a Redux function that creates the store by passing in the reducer(s).
Step 4: Connect Redux with React Using react-redux
To connect the Redux store to React, we will use the Provider component from react-redux. This will make the Redux store available to all components in the app.
1. Wrap Your Application with Provider
In src/index.js, import the Provider component from react-redux and the store from redux/store.js. Then, wrap your app with the Provider:
js// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import store from './redux/store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Providermakes the Redux store available to any nested components.
2. Connect Redux State to Your Component
Now, in src/App.js, we’ll access the Redux state (the count value) and dispatch actions (increment and decrement) from our component. We will use the useSelector hook to read from the Redux state and the useDispatch hook to send actions to the store.
js// src/App.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { increment, decrement } from './redux/actions';
function App() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div className="App">
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
}
export default App;
useSelectorallows you to access the Redux store state. In this case, we select thecountvalue.useDispatchgives you access to thedispatchfunction, which you can use to send actions to the store.- When you click the Increment or Decrement button, the appropriate action will be dispatched to the Redux store, and the state will update accordingly.
Step 5: Run the Application
Run the application with the following command:
bashnpm startOpen your browser and visit
http://localhost:3000/. You should see a simple counter app that allows you to increment and decrement the count, with the state managed by Redux.
Step 6: Explanation of Key Redux Concepts
- State: The state is managed in a central store and is immutable. Instead of directly modifying the state, you dispatch actions, and the reducers return a new state based on those actions.
- Action Creators: Functions that return action objects. They help centralize the action logic and make it easier to dispatch actions.
- Reducers: Functions that handle state changes based on actions. They receive the current state and the action as arguments and return a new state.
useSelector: A React-Redux hook that allows components to read from the Redux store.useDispatch: A React-Redux hook used to dispatch actions to the store.
Step 7: Enhancements
You can enhance this app further by:
- Adding async actions with
redux-thunk: For handling asynchronous operations like API calls. - Using
combineReducers: If your app grows and you need to manage multiple pieces of state, combine reducers. - Using dev tools: You can install the Redux DevTools Extension to debug the Redux store interactively.
Conclusion
In this tutorial, we’ve created a simple counter application using React.js and Redux. You’ve learned how to set up Redux, create actions, reducers, and the store, and connect Redux to React components using react-redux.
Redux is a powerful tool for managing global state in React applications, especially as they grow in complexity. It helps keep your state predictable, maintainable, and scalable.
If you’re building larger applications, this basic setup can be expanded with more advanced features like Redux Middleware, redux-toolkit, or async actions with redux-thunk.
You said:
ChatGPT said:
React.js Basic Tutorial with Example
React is a popular JavaScript library for building user interfaces, particularly for single-page applications (SPAs) where you need a fast, interactive user experience. React allows you to build UI components that can update dynamically without needing to reload the whole page.
In this tutorial, we'll walk through the basic concepts of React and build a simple app from scratch. This example will include the following topics:
- Setting up a React project.
- Creating components.
- Using props and state.
- Handling events.
- Using hooks (specifically
useState).
Step 1: Setting Up a React Project
To start working with React, the easiest way is to use Create React App, a tool that sets up everything for you.
Open your terminal and run the following command to create a new React app:
bashnpx create-react-app react-basic-tutorialThis will create a new folder called
react-basic-tutorialwith all the necessary files and dependencies for your React app.After the setup is complete, navigate into the new folder:
bashcd react-basic-tutorialNow, start the development server:
bashnpm startThis will run the app and open it in your default web browser at
http://localhost:3000.
Step 2: Understanding the Folder Structure
The folder structure of a React app generated by Create React App looks like this:
javareact-basic-tutorial/
├── node_modules/
├── public/
│ └── index.html
├── src/
│ ├── App.js
│ ├── index.js
│ ├── App.css
│ └── ...
└── package.json
- public/index.html: This is the main HTML file. React components are rendered into the
divwith theid="root". - src/index.js: This is the entry point for the React app. It renders the main
Appcomponent. - src/App.js: This is the default app component, where we can define our main UI and logic.
Step 3: Creating a Simple Component
A component in React is a function (or a class) that returns a piece of UI (JSX) that will be rendered to the screen. We can create a simple component to display a message.
Open
src/App.jsand modify it as follows:js// src/App.js import React from 'react'; function App() { return ( <div className="App"> <h1>Hello, welcome to React!</h1> </div> ); } export default App;Now, when you save the file, React will re-render the app and display the message on the page. This is the simplest form of a component that returns some static content.
Step 4: Using Props
Props (short for "properties") allow you to pass data from a parent component to a child component. Let’s create a component that takes in a name prop and displays a greeting message.
First, create a new component called
Greeting.jsinside thesrcfolder:js// src/Greeting.js import React from 'react'; function Greeting(props) { return <h2>Hello, {props.name}!</h2>; } export default Greeting;- This component receives
propsand renders a greeting message using thenameprop.
- This component receives
Now, go back to
App.jsand use theGreetingcomponent, passing anameprop:js// src/App.js import React from 'react'; import Greeting from './Greeting'; function App() { return ( <div className="App"> <h1>Welcome to React!</h1> <Greeting name="John" /> <Greeting name="Sarah" /> </div> ); } export default App;When you save the file, the app will display two greeting messages:
cssWelcome to React! Hello, John! Hello, Sarah!
This demonstrates how you can reuse the Greeting component and pass different values for the name prop.
Step 5: Using State with useState Hook
State in React allows components to store data that can change over time. The useState hook is used to add state to functional components. Let's modify our app to include a counter with buttons to increase and decrease the count.
In
App.js, import theuseStatehook and create a state variable for the count:js// src/App.js import React, { useState } from 'react'; import Greeting from './Greeting'; function App() { // Declare a state variable 'count' with an initial value of 0 const [count, setCount] = useState(0); // Functions to handle increment and decrement const increment = () => setCount(count + 1); const decrement = () => setCount(count - 1); return ( <div className="App"> <h1>React State Example</h1> <Greeting name="John" /> <p>Current count: {count}</p> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ); } export default App;In this code:
useState(0)creates a state variablecountwith an initial value of0.setCountis the function that will update thecountvalue.incrementanddecrementare functions that modify thecountstate when the buttons are clicked.- The
onClickevent handlers call these functions when the user clicks the buttons.
When you save and run the app, you’ll see the following:
- A
Current countvalue. - Buttons to Increment and Decrement the count.
- A
Step 6: Handling Events
React allows you to handle user interactions, like clicks, form submissions, and keyboard inputs, with event handlers. We've already seen the onClick event in action with the increment and decrement buttons.
Let's add an input field that updates the greeting message dynamically when the user types their name.
Update
App.jsto include an input field that updates thenamestate:js// src/App.js import React, { useState } from 'react'; import Greeting from './Greeting'; function App() { const [count, setCount] = useState(0); const [name, setName] = useState(''); const increment = () => setCount(count + 1); const decrement = () => setCount(count - 1); const handleInputChange = (event) => { setName(event.target.value); // Update the name state as the user types }; return ( <div className="App"> <h1>React Event Handling Example</h1> <Greeting name={name || "Guest"} /> {/* Default to "Guest" if name is empty */} <input type="text" value={name} onChange={handleInputChange} placeholder="Enter your name" /> <p>Current count: {count}</p> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ); } export default App;Here:
- We added a new state variable
namewith theuseStatehook to store the name entered by the user. - The
handleInputChangefunction updates thenamestate as the user types in the input field. - We use the
namestate as a prop for theGreetingcomponent to dynamically update the greeting message.
- We added a new state variable
When you run the app:
- You will see a text input where you can type a name.
- The greeting message will update in real-time as you type.
- The count can still be incremented and decremented.
Conclusion
In this tutorial, you learned the following basic concepts of React:
- Components: Building blocks of a React app.
- Props: Passing data from parent to child components.
- State: Managing data within components using the
useStatehook. - Event Handling: Responding to user interactions like button clicks and input changes.
By combining these concepts, you can start building more interactive and dynamic web applications with React. As you continue learning React, you can explore more advanced topics like component lifecycle, useEffect hook, context API, routing with React Router, and state management with Redux.
- Get link
- X
- Other Apps
Comments
Post a Comment