React js redux tutorial

 

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

  1. Create a new React app using Create React App (CRA) CLI tool:

    bash
    npx create-react-app react-redux-tutorial cd react-redux-tutorial
  2. Install Redux and React-Redux (the official Redux bindings for React):

    bash
    npm 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:

  1. Store: A central place where the entire state of the application lives.
  2. Actions: Plain JavaScript objects that describe "what happened" in the application (e.g., user interactions or network requests).
  3. Reducers: Functions that specify how the state of the application changes in response to an action.
  4. Dispatch: A function used to send an action to the Redux store.
  5. 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 type property 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 count state 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;
  • createStore is 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') );
  • Provider makes 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;
  • useSelector allows you to access the Redux store state. In this case, we select the count value.
  • useDispatch gives you access to the dispatch function, 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

  1. Run the application with the following command:

    bash
    npm start
  2. Open 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:
React basic tutorial with example
ChatGPT said:
ChatGPT

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:

  1. Setting up a React project.
  2. Creating components.
  3. Using props and state.
  4. Handling events.
  5. 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.

  1. Open your terminal and run the following command to create a new React app:

    bash
    npx create-react-app react-basic-tutorial

    This will create a new folder called react-basic-tutorial with all the necessary files and dependencies for your React app.

  2. After the setup is complete, navigate into the new folder:

    bash
    cd react-basic-tutorial
  3. Now, start the development server:

    bash
    npm start

    This 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:

java
react-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 div with the id="root".
  • src/index.js: This is the entry point for the React app. It renders the main App component.
  • 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.

  1. Open src/App.js and 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;
  2. 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.

  1. First, create a new component called Greeting.js inside the src folder:

    js
    // src/Greeting.js import React from 'react'; function Greeting(props) { return <h2>Hello, {props.name}!</h2>; } export default Greeting;
    • This component receives props and renders a greeting message using the name prop.
  2. Now, go back to App.js and use the Greeting component, passing a name prop:

    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;
  3. When you save the file, the app will display two greeting messages:

    css
    Welcome 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.

  1. In App.js, import the useState hook 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;
  2. In this code:

    • useState(0) creates a state variable count with an initial value of 0.
    • setCount is the function that will update the count value.
    • increment and decrement are functions that modify the count state when the buttons are clicked.
    • The onClick event handlers call these functions when the user clicks the buttons.
  3. When you save and run the app, you’ll see the following:

    • A Current count value.
    • Buttons to Increment and Decrement the count.

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.

  1. Update App.js to include an input field that updates the name state:

    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;
  2. Here:

    • We added a new state variable name with the useState hook to store the name entered by the user.
    • The handleInputChange function updates the name state as the user types in the input field.
    • We use the name state as a prop for the Greeting component to dynamically update the greeting message.
  3. 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:

  1. Components: Building blocks of a React app.
  2. Props: Passing data from parent to child components.
  3. State: Managing data within components using the useState hook.
  4. 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.

Comments

Popular posts from this blog

Top 200 telagu words in hindi daily life?

Building strong foundational knowledge in frontend development topics

Docker and Kubernetes Tutorials and QnA