Immutability

اللاتحوير (Immutability)

Intermediateprogramming1 min read
immutablepure datareadonlyfrozen objectvalue object

Definition

The principle of not modifying data in place — creating new copies with changes instead of altering the original.

مبدأ عدم تعديل البيانات في مكانها — إنشاء نسخ جديدة مع التغييرات بدلاً من تغيير الأصل.

Why It Matters

Mutating React state directly is one of the most common bugs beginners make. `project.title = 'New'` won't trigger a re-render — `setProject({ ...project, title: 'New' })` will.

تحوير حالة React مباشرةً هو أحد أكثر الأخطاء شيوعًا للمبتدئين. `project.title = 'New'` لن يُشغّل إعادة التصيير — `setProject({ ...project, title: 'New' })` سيفعل.

Full Definition

Immutability means never mutating data structures directly. Instead, create new copies with the changes applied. In React, state must be updated immutably: `setState({ ...state, field: value })` not `state.field = value`. React uses reference equality to detect changes — mutating in place breaks re-renders. Firestore also encourages immutable patterns with batch.set() and transaction.
اللاتحوير يعني عدم تغيير هياكل البيانات مباشرةً. بدلاً من ذلك، أنشئ نسخًا جديدة مع التغييرات المطبّقة. في React، يجب تحديث الحالة بشكل غير متحوّر: `setState({ ...state, field: value })` وليس `state.field = value`.

Example Usage

// WRONG: terms[0].difficulty = 'advanced'; // RIGHT: setTerms(terms.map(t => t.slug === slug ? { ...t, difficulty: 'advanced' } : t))

// خطأ: terms[0].difficulty = 'advanced'; // صحيح: setTerms(terms.map(t => t.slug === slug ? { ...t, difficulty: 'advanced' } : t))

Knowledge Graph

Avoid these mistakes when using Immutability:

1

Pushing to a state array directly: `items.push(x)` — React won't detect this change

2

Thinking spreading is deep clone — nested objects still share references

Sign in to unlock guided AI explanations from AI Teacher.

Generate a Prompt

Copy this prompt and use it directly with any AI model — no setup needed.

Ready-to-Use Prompt
Help me build a project using Immutability.

Explain:
1. What is Immutability and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Pushing to a state array directly: `items.push(x)` — React won't detect this change, Thinking spreading is deep clone — nested objects still share references
5. Best practices and production tips

Official Resources