惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
N
Netflix TechBlog - Medium
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
J
Java Code Geeks
V
Visual Studio Blog
H
Help Net Security
Engineering at Meta
Engineering at Meta
Hugging Face - Blog
Hugging Face - Blog
Microsoft Security Blog
Microsoft Security Blog
腾讯CDC
博客园 - 【当耐特】
B
Blog
Stack Overflow Blog
Stack Overflow Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
大猫的无限游戏
大猫的无限游戏
GbyAI
GbyAI
博客园 - 司徒正美
博客园 - 叶小钗
Y
Y Combinator Blog
MyScale Blog
MyScale Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
G
Google Developers Blog
酷 壳 – CoolShell
酷 壳 – CoolShell

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
1 RN Thing a Day – Day 14: Predicate & Effect Patterns in...
Ola Abaza · 2026-05-24 · via DEV Community

The easiest way to think about it is:

Predicate = Watch for something

Effect = Do something when it happens

Example:

predicate: Is someone entering the building?
effect: Check their ID

Enter fullscreen mode Exit fullscreen mode

Example 1: Add Item To Cart

// cartSlice.ts

import { createSlice, PayloadAction } from '@reduxjs/toolkit'

interface Product {
  id: string
  name: string
}

interface CartState {
  items: Product[]
}

const initialState: CartState = {
  items: []
}

const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {
    addItem: (state, action: PayloadAction<Product>) => {
      state.items.push(action.payload)
    },

    removeItem: (state, action: PayloadAction<string>) => {
      state.items = state.items.filter(
        item => item.id !== action.payload
      )
    }
  }
})

export const { addItem, removeItem } = cartSlice.actions

export default cartSlice.reducer

// listenerMiddleware.ts

import { createListenerMiddleware } from '@reduxjs/toolkit'
import Toast from 'react-native-toast-message'

export const listenerMiddleware =
  createListenerMiddleware()

// cartListeners.ts

import { listenerMiddleware } from './listenerMiddleware'

listenerMiddleware.startListening({
  predicate: (_, currentState, previousState) => {
    return (
      currentState.cart.items.length >
      previousState.cart.items.length
    )
  },

  effect: async () => {
    Toast.show({
      type: 'success',
      text1: 'Item added to cart'
    })
  }
})

Enter fullscreen mode Exit fullscreen mode

Why use a predicate instead of listening to addItem directly?
You could do:

listenerMiddleware.startListening({
  actionCreator: addItem,
  effect: () => {
    Toast.show({
      type: 'success',
      text1: 'Item added to cart'
    })
  }
})

Enter fullscreen mode Exit fullscreen mode

But the predicate version is more powerful because it reacts to state changes, not specific actions.

The predicate doesn't know or care which action happened. It only cares about the resulting state.

For example, if items are added by:

dispatch(addItem(product))
dispatch(syncCartFromServer())
dispatch(restoreSavedCart())

Enter fullscreen mode Exit fullscreen mode

the same predicate still works:

currentState.cart.items.length >
previousState.cart.items.length

Enter fullscreen mode Exit fullscreen mode

because it only cares that the cart grew, regardless of which action caused it. That's the main strength of the Predicate & Effect pattern.

Why Compare Current State and Previous State?
Because many actions happen in the app.

For example: User adds item to cart

Enter fullscreen mode Exit fullscreen mode

Without comparing states, your effect might run every time.

Instead, the predicate asks:

Did the specific thing I care about change?

Enter fullscreen mode Exit fullscreen mode

Only then does it execute the effect.

When should I use actionCreator?
Use it when your business rule is: "When this action happens, do something."

Examples:


Track Login Event
startListening({
  actionCreator: loginSuccess,
  effect: () => {
    Analytics.track('Login')
  }
})

Enter fullscreen mode Exit fullscreen mode

You specifically want to react to the login action.

When should I use predicate?
Use it when your business rule is:"When the state becomes this, do something."

Examples:

User Became Logged In
predicate: (_, current, previous) =>
  !previous.app.isLoggedIn &&
  current.app.isLoggedIn

Enter fullscreen mode Exit fullscreen mode

Maybe several actions can lead to a logged-in state:

loginSuccess()
restoreSession()
refreshTokenSuccess()

Enter fullscreen mode Exit fullscreen mode

You don't want to listen to all of them.

You just care that: isLoggedIn changed from false to true

Why not just use useEffect?

For small apps, useEffect is often enough. Predicate & Effect becomes valuable when you want to move business logic outside the UI layer.

The Problem With useEffect
Imagine this: When a user logs in, you need to:

Fetch profile
Load permissions
Connect websocket
Start analytics session

Many developers write:

function HomeScreen() {
  const isLoggedIn = useSelector(selectIsLoggedIn)

  useEffect(() => {
    if (isLoggedIn) {
      dispatch(fetchProfile())
      dispatch(loadPermissions())
      connectWebSocket()
      startAnalytics()
    }
  }, [isLoggedIn])
}

Enter fullscreen mode Exit fullscreen mode

Now ask yourself:

Why is HomeScreen responsible for login behavior?

It isn't really a UI concern.

It's application behavior.

The app should perform these actions whenever a user becomes logged in, regardless of which screen is mounted.

This is where Predicate & Effect shines.

Simple Rule

Use useEffect when:

The effect belongs to the component.

Examples:

  • Focus input
  • Start animation
  • Listen to keyboard
  • Set navigation title
  • Fetch data only for this screen

Use Predicate & Effect when:
The effect belongs to the application.

Examples:

  • User logged in
  • User logged out
  • Network restored
  • Language changed
  • Permissions updated
  • Token expired
  • Cart became non-empty
  • Analytics tracking
  • Background synchronization