Skip to main content

Python print() Function

When you start learning Python, one of the first things you need to learn is how to display information on the screen. For example, you might want to display: A welcome message. Your name and age. The result of a mathematical calculation. Student marks and results. Information generated by a Python program. Python provides a built-in function called print() for displaying information. The print() function is one of the simplest and most frequently used functions in Python. It helps programmers display information while testing programs, solving problems, and developing applications. In this article, we will learn how to use print() with practical examples and their outputs. 1. What Is the print() Function in Python? The print() function is a built-in Python function that displays information in the output area, usually the terminal or console. Let's look at a simple example. print("Hello, World!") Output: Hello, World! In this example, Python displays the text Hello,...

State Management in React Using Context API and Redux Toolkit

Introduction

In the previous article, we learned:

  • File uploads

  • Multer

  • Cloudinary integration

  • Image handling

  • FormData

  • Media storage systems

Now it is time to learn one of the most important concepts in large React applications:

State Management

As applications grow larger, managing data between multiple components becomes difficult.

Examples:

  • User authentication

  • Shopping cart

  • Theme settings

  • Notifications

  • User profile data

Passing data manually through many components becomes messy.

To solve this problem, React applications use:

  • Context API

  • Redux Toolkit

In this article, we will learn:

  • What state management is

  • Local vs global state

  • Context API

  • useContext Hook

  • Redux Toolkit

  • Redux store

  • Actions and reducers

  • Managing authentication globally


What is State?

State means:

Data that changes dynamically

Examples:

  • Counter value

  • Logged-in user

  • Theme color

  • API response data


What is State Management?

State management means:

Managing and sharing application data efficiently

Local State vs Global State

Local StateGlobal State
Used in one componentUsed across app
useState()Context / Redux
Small dataLarge shared data

Problems Without State Management

Suppose authentication data is needed in:

  • Navbar

  • Dashboard

  • Profile page

  • Sidebar

Passing props repeatedly creates:

Props Drilling

What is Props Drilling?

Props drilling means:

Passing props through multiple unnecessary components

Example:

App
 ↓
Dashboard
 ↓
Sidebar
 ↓
Profile

This becomes difficult to manage.


What is Context API?

React Context helps share data globally without props drilling.


Why Context API is Useful

Context API helps:

  • Share authentication

  • Manage themes

  • Store user data

  • Avoid repeated props


Creating Context Folder

Inside React project:

src
│
├── context

Creating Auth Context

Create:

AuthContext.js

Basic Context Setup

import {
    createContext,
    useState
} from 'react';

export const AuthContext = createContext();

function AuthProvider({ children }) {

    const [isAuthenticated,
    setIsAuthenticated] = useState(false);

    return (

        <AuthContext.Provider
            value={{
                isAuthenticated,
                setIsAuthenticated
            }}
        >

            {children}

        </AuthContext.Provider>
    );
}

export default AuthProvider;

Understanding createContext()

createContext()

creates global data storage.


Understanding Provider

<AuthContext.Provider>

shares data with all components.


Wrapping App with Provider

Inside:

src/index.js
import React from 'react';

import ReactDOM from 'react-dom/client';

import App from './App';

import AuthProvider from './context/AuthContext';

const root = ReactDOM.createRoot(
    document.getElementById('root')
);

root.render(

    <AuthProvider>

        <App />

    </AuthProvider>
);

Using Context Data

React provides:

useContext()

Example

import {
    useContext
} from 'react';

import {
    AuthContext
} from './context/AuthContext';

function Navbar() {

    const {
        isAuthenticated
    } = useContext(AuthContext);

    return (

        <div>

            {
                isAuthenticated
                ? 'Logged In'
                : 'Guest'
            }

        </div>
    );
}

How Context API Works

Provider Stores Data
        ↓
Components Access Data
        ↓
UI Updates Automatically

Limitations of Context API

Context API works well for:

  • Small applications

  • Medium applications

But large enterprise applications often use:

Redux

What is Redux?

Redux is a powerful global state management library.


Why Redux is Popular

Redux helps:

  • Manage large state

  • Organize application logic

  • Debug easily

  • Scale applications


What is Redux Toolkit?

Redux Toolkit simplifies Redux development.

Old Redux required:

  • Too much boilerplate code

  • Complex setup

Redux Toolkit solves these problems.


Installing Redux Toolkit

Inside client folder:

npm install @reduxjs/toolkit react-redux

Understanding Packages

PackagePurpose
@reduxjs/toolkitRedux setup
react-reduxConnect React with Redux

Redux Core Concepts

ConceptMeaning
StoreGlobal state
ActionWhat happened
ReducerUpdates state
DispatchSends action

Understanding Redux Flow

Component
    ↓
Dispatch Action
    ↓
Reducer
    ↓
Store Updated
    ↓
UI Re-render

Creating Redux Folder Structure

src
│
├── app
├── features

Creating Store

Create:

app/store.js

Redux Store Setup

import {
    configureStore
} from '@reduxjs/toolkit';

export const store = configureStore({

    reducer: {}
});

What is configureStore()?

configureStore()

creates Redux store.


What is a Slice?

Redux Toolkit uses:

Slices

A slice contains:

  • State

  • Reducers

  • Actions


Creating Auth Slice

Create:

features/authSlice.js

Example Auth Slice

import {
    createSlice
} from '@reduxjs/toolkit';

const initialState = {

    isAuthenticated: false
};

const authSlice = createSlice({

    name: 'auth',

    initialState,

    reducers: {

        login: (state) => {

            state.isAuthenticated = true;
        },

        logout: (state) => {

            state.isAuthenticated = false;
        }
    }
});

export const {
    login,
    logout
} = authSlice.actions;

export default authSlice.reducer;

Understanding createSlice()

createSlice()

automatically creates:

  • Reducers

  • Actions


Adding Reducer to Store

import authReducer from
'../features/authSlice';

export const store = configureStore({

    reducer: {

        auth: authReducer
    }
});

Connecting Redux with React

Inside:

src/index.js
import { Provider } from 'react-redux';

import { store } from './app/store';

root.render(

    <Provider store={store}>

        <App />

    </Provider>
);

Using Redux State

React Redux provides:

useSelector()

Example

import {
    useSelector
} from 'react-redux';

function Navbar() {

    const isAuthenticated = useSelector(

        (state) => state.auth.isAuthenticated
    );

    return (
        <h1>{isAuthenticated ? 'User' : 'Guest'}</h1>
    );
}

Updating Redux State

React Redux provides:

useDispatch()

Example Login Action

import {
    useDispatch
} from 'react-redux';

import {
    login
} from './features/authSlice';

function Login() {

    const dispatch = useDispatch();

    return (

        <button
            onClick={() => dispatch(login())}
        >

            Login

        </button>
    );
}

Redux Authentication Flow

User Logs In
      ↓
Dispatch login Action
      ↓
Redux Store Updates
      ↓
All Components Update

Context API vs Redux

Context APIRedux Toolkit
Simple setupMore scalable
Small projectsLarge projects
Built into ReactExternal library
Less boilerplatePowerful architecture

When to Use Context API

Use Context API for:

  • Themes

  • Authentication

  • Language settings


When to Use Redux

Use Redux for:

  • Large applications

  • Complex API data

  • Shopping carts

  • Dashboards

  • Enterprise apps


Best Practices

Keep State Organized

Separate:

  • Auth state

  • User state

  • Product state


Avoid Unnecessary Global State

Not every data belongs in Redux.


Use Redux Toolkit

Modern Redux development should always use:

Redux Toolkit

Create Separate Slices

Example:

  • authSlice

  • productSlice

  • cartSlice


Common Beginner Mistakes

Storing Everything in Redux

Only global data should use Redux.


Mutating State Incorrectly

Redux Toolkit handles immutable updates automatically.


Forgetting Provider

Without:

<Provider>

Redux will not work.


Real-World Applications

Redux is used in:

  • E-commerce websites

  • Banking dashboards

  • Social media apps

  • SaaS platforms

  • Learning management systems


Conclusion

You have now learned advanced state management in React using:

  • Context API

  • Redux Toolkit

You learned:

  • Global state management

  • Redux store

  • Actions

  • Reducers

  • Slices

  • Authentication management

  • useSelector()

  • useDispatch()

Now your React applications are becoming scalable, organized, and enterprise-ready.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? 📌 Readability – Comments make code easier to understand for you and others. 📌 Maintenance – When you revisit your code after months, comments remind you what you were doing. 📌 Collaboration – In team projects, comments explain code to fellow developers. 📌 Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . 💻 Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } 🧠 Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

💡 Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. 🧑‍💻 Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...