کانال نوحه و مداحی ناب

۳ مطلب در خرداد ۱۴۰۴ ثبت شده است

  • how to use custume useEffect in react .js

    i want to write myUseEffect and use it instead of useEffect?

    Great idea! You can create your own custom hook myUseEffect to replace useEffect. This is useful if you want to add extra functionality, such as logging, dependency tracking, or conditional execution.

     

    ✅ Step 1: Define myUseEffect Hook

    Wrap useEffect inside a custom hook with added logic:

    js

    import { useEffect } from "react";
    
    const myUseEffect = (callback, dependencies) => {
      useEffect(() => {
        console.log("Custom useEffect triggered!"); // ✅ Optional logging
        return callback();
      }, dependencies);
    };
    
    export default myUseEffect;
    
     

    ✅ Step 2: Use myUseEffect in Your Component

    Replace standard useEffect with your custom hook:

    js

    import myUseEffect from "./myUseEffect";
    
    const MyComponent = () => {
      myUseEffect(() => {
        console.log("Effect has run!");
      }, []);
    
      return <h2>Custom useEffect in Action!</h2>;
    };
    
     

    🚀 Why Use This Custom Hook?

    ✅ Adds logging to track when useEffect runs ✅ Allows extra logic before executing the effect ✅ Reusable across multiple components

    Would you like help adding specific optimizations or conditions to myUseEffect?

    نمايش: ۹
  • how to use custume useDispatch in react .js

    and i want to write myUseDispatch AND USE IT INSTEAD OF useDispatch?

    Great idea! You can create a custom hook myUseDispatch to replace useDispatch and add extra functionality, such as logging or modifying actions before dispatching.

     

    ✅ Step 1: Create myUseDispatch.js

    Wrap useDispatch inside a custom hook with added logic:

    js

    import { useDispatch } from "react-redux";
    
    const myUseDispatch = () => {
      const dispatch = useDispatch();
    
      return (action) => {
        console.log("Dispatching action:", action); // ✅ Logs action before dispatching
        dispatch(action);
      };
    };
    
    export default myUseDispatch;
    
     

    ✅ Step 2: Use myUseDispatch in Your Component

    Replace useDispatch with your custom myUseDispatch:

    js

    import myUseDispatch from "./myUseDispatch";
    import { setToken } from "./redux/authSlice";
    
    const MyComponent = () => {
      const dispatch = myUseDispatch();
    
      const handleLogin = () => {
        dispatch(setToken("my-secure-token")); // ✅ Dispatch action using custom hook
      };
    
      return <button onClick={handleLogin}>Login</button>;
    };
    
     

    🚀 Why Use This Custom Hook?

    ✅ Adds logging to track dispatched actions ✅ Allows modification of actions before dispatching ✅ Reusable across multiple components

    Would you like help adding middleware-like logic to intercept and modify actions before dispatching?

     

    نمايش: ۱۰
  • best way of handling access token in react .js?

    best way of handling access token in react .js?

    Managing access tokens securely in React is crucial to prevent security risks like token theft and unauthorized access. Here’s the best approach depending on your authentication strategy:

     

    1️⃣ Store Tokens Securely

    Instead of localStorage, consider safer alternatives:

    HttpOnly Cookies (Recommended)

    • Tokens are stored on the server and not accessible to JavaScript, preventing XSS attacks.

    • Use SameSite=Strict and Secure flags for better protection.

    Session Storage (Better Than LocalStorage)

    • Clears automatically when the session ends.

    • Still accessible by JavaScript, so not ideal for highly sensitive tokens.

    Redux or React State (For Short-Lived Tokens)

    • Stores tokens in memory, preventing exposure to persistent storage attacks.

    • Good for apps using short-lived tokens and refresh mechanisms.

     

    2️⃣ Implement Token Expiry & Refresh Mechanism

    To avoid stale tokens and frequent logouts, implement token refreshing using refresh tokens.

    🔹 Example: Automatic Token Refresh with Axios Interceptors

    javascript

    import axios from 'axios';
    
    // Create an Axios instance
    const api = axios.create({
      baseURL: 'https://your-api.com',
      withCredentials: true // Ensures cookies are sent
    });
    
    // Request interceptor to attach token
    api.interceptors.request.use(config => {
      const accessToken = sessionStorage.getItem("access_token");
      if (accessToken) {
        config.headers.Authorization = `Bearer ${accessToken}`;
      }
      return config;
    });
    
    // Response interceptor to handle token expiry
    api.interceptors.response.use(
      response => response,
      async error => {
        if (error.response?.status === 401) {
          // Try refreshing the token
          const refreshToken = sessionStorage.getItem("refresh_token");
          if (refreshToken) {
            const { data } = await axios.post("https://your-api.com/refresh", { refresh_token: refreshToken });
            sessionStorage.setItem("access_token", data.access_token);
            error.config.headers.Authorization = `Bearer ${data.access_token}`;
            return api(error.config); // Retry original request
          }
        }
        return Promise.reject(error);
      }
    );
    
    export default api;
    
     

    3️⃣ Protect Routes with Authentication Checks

    Ensure users are redirected if their token is missing or expired.

    🔹 Example: Private Route Protection

    javascript

    import { Navigate, Outlet } from "react-router-dom";
    
    const PrivateRoute = () => {
      const accessToken = sessionStorage.getItem("access_token");
    
      return accessToken ? <Outlet /> : <Navigate to="/login" />;
    };
    
    export default PrivateRoute;
    
     

    ✅ Summary of Best Practices

    🔒 Store tokens securely (HttpOnly Cookies or Session Storage) 🔄 Use a refresh token system to prevent forced logouts 🚀 Protect routes with authentication checks 📡 Use Axios interceptors for automatic token handling

     

    نمايش: ۱۵