useResetRecoilState #

什么是 useResetRecoilState? #

useResetRecoilState 是一个 Hook,用于重置 Recoil 状态到其默认值。它返回一个重置函数,调用该函数会将状态重置为初始状态。

jsx
const resetState = useResetRecoilState(state);

基本用法 #

重置 Atom #

jsx
import { atom, useRecoilState, useResetRecoilState } from 'recoil';

const countState = atom({
  key: 'countState',
  default: 0,
});

function Counter() {
  const [count, setCount] = useRecoilState(countState);
  const resetCount = useResetRecoilState(countState);
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
      <button onClick={resetCount}>Reset</button>
    </div>
  );
}

重置对象状态 #

jsx
const formState = atom({
  key: 'formState',
  default: {
    username: '',
    email: '',
    password: '',
  },
});

function Form() {
  const [form, setForm] = useRecoilState(formState);
  const resetForm = useResetRecoilState(formState);
  
  return (
    <form>
      <input
        value={form.username}
        onChange={(e) => setForm({ ...form, username: e.target.value })}
      />
      <input
        value={form.email}
        onChange={(e) => setForm({ ...form, email: e.target.value })}
      />
      <button type="button" onClick={resetForm}>
        Clear Form
      </button>
    </form>
  );
}

性能优势 #

useResetRecoilState 不会订阅状态变化:

jsx
function ResetButton() {
  const resetCount = useResetRecoilState(countState);
  
  console.log('This only logs once on mount');
  
  return <button onClick={resetCount}>Reset</button>;
}

实战示例:表单重置 #

jsx
import { atom, useRecoilState, useResetRecoilState } from 'recoil';

const contactFormState = atom({
  key: 'contactForm',
  default: {
    name: '',
    email: '',
    subject: '',
    message: '',
  },
});

function ContactForm() {
  const [form, setForm] = useRecoilState(contactFormState);
  const resetForm = useResetRecoilState(contactFormState);
  
  const handleChange = (field) => (e) => {
    setForm(prev => ({ ...prev, [field]: e.target.value }));
  };
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    try {
      await submitForm(form);
      alert('Form submitted successfully!');
      resetForm();
    } catch (error) {
      alert('Failed to submit form');
    }
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input
        value={form.name}
        onChange={handleChange('name')}
        placeholder="Name"
      />
      <input
        value={form.email}
        onChange={handleChange('email')}
        placeholder="Email"
      />
      <input
        value={form.subject}
        onChange={handleChange('subject')}
        placeholder="Subject"
      />
      <textarea
        value={form.message}
        onChange={handleChange('message')}
        placeholder="Message"
      />
      <button type="submit">Submit</button>
      <button type="button" onClick={resetForm}>Clear</button>
    </form>
  );
}

实战示例:多状态重置 #

jsx
import { atom, useResetRecoilState, useRecoilValue } from 'recoil';

const userSettingsState = atom({
  key: 'userSettings',
  default: {
    theme: 'light',
    language: 'en',
    notifications: true,
  },
});

const userPreferencesState = atom({
  key: 'userPreferences',
  default: {
    fontSize: 16,
    compactMode: false,
  },
});

function ResetAllButton() {
  const resetSettings = useResetRecoilState(userSettingsState);
  const resetPreferences = useResetRecoilState(userPreferencesState);
  
  const resetAll = () => {
    resetSettings();
    resetPreferences();
  };
  
  return <button onClick={resetAll}>Reset All to Default</button>;
}

实战示例:购物车清空 #

jsx
import { atom, useRecoilValue, useResetRecoilState } from 'recoil';

const cartState = atom({
  key: 'cart',
  default: [],
});

function CartSummary() {
  const cart = useRecoilValue(cartState);
  const resetCart = useResetRecoilState(cartState);
  
  const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  
  const handleCheckout = async () => {
    await checkout(cart);
    resetCart();
  };
  
  return (
    <div>
      <p>Items: {cart.length}</p>
      <p>Total: ${total}</p>
      <button onClick={handleCheckout}>Checkout</button>
      <button onClick={resetCart}>Clear Cart</button>
    </div>
  );
}

实战示例:搜索过滤器重置 #

jsx
import { atom, useRecoilState, useResetRecoilState, useRecoilValue } from 'recoil';

const searchFiltersState = atom({
  key: 'searchFilters',
  default: {
    query: '',
    category: 'all',
    priceRange: { min: 0, max: 10000 },
    sortBy: 'relevance',
    inStock: false,
  },
});

function SearchFilters() {
  const [filters, setFilters] = useRecoilState(searchFiltersState);
  const resetFilters = useResetRecoilState(searchFiltersState);
  
  return (
    <div className="filters">
      <input
        value={filters.query}
        onChange={(e) => setFilters({ ...filters, query: e.target.value })}
        placeholder="Search..."
      />
      
      <select
        value={filters.category}
        onChange={(e) => setFilters({ ...filters, category: e.target.value })}
      >
        <option value="all">All Categories</option>
        <option value="electronics">Electronics</option>
        <option value="clothing">Clothing</option>
      </select>
      
      <select
        value={filters.sortBy}
        onChange={(e) => setFilters({ ...filters, sortBy: e.target.value })}
      >
        <option value="relevance">Relevance</option>
        <option value="price-asc">Price: Low to High</option>
        <option value="price-desc">Price: High to Low</option>
      </select>
      
      <label>
        <input
          type="checkbox"
          checked={filters.inStock}
          onChange={(e) => setFilters({ ...filters, inStock: e.target.checked })}
        />
        In Stock Only
      </label>
      
      <button onClick={resetFilters}>Clear Filters</button>
    </div>
  );
}

与 useSetRecoilState 结合 #

jsx
import { DefaultValue } from 'recoil';

function FormActions() {
  const setForm = useSetRecoilState(formState);
  const resetForm = useResetRecoilState(formState);
  
  const clearForm = () => {
    setForm(new DefaultValue());
  };
  
  return (
    <div>
      <button onClick={resetForm}>Reset (Hook)</button>
      <button onClick={clearForm}>Clear (DefaultValue)</button>
    </div>
  );
}

TypeScript 支持 #

tsx
import { atom, useResetRecoilState } from 'recoil';

interface FormState {
  username: string;
  email: string;
  password: string;
}

const formState = atom<FormState>({
  key: 'formState',
  default: {
    username: '',
    email: '',
    password: '',
  },
});

function ResetButton() {
  const resetForm = useResetRecoilState(formState);
  
  return <button onClick={resetForm}>Reset Form</button>;
}

完整示例:设置面板 #

jsx
import { atom, useRecoilState, useResetRecoilState, useRecoilValue } from 'recoil';

const settingsState = atom({
  key: 'settings',
  default: {
    theme: 'light',
    fontSize: 16,
    language: 'en',
    notifications: {
      email: true,
      push: true,
      sms: false,
    },
    privacy: {
      showProfile: true,
      showActivity: false,
    },
  },
});

function SettingsPanel() {
  const [settings, setSettings] = useRecoilState(settingsState);
  const resetSettings = useResetRecoilState(settingsState);
  
  const updateTheme = (theme) => {
    setSettings(prev => ({ ...prev, theme }));
  };
  
  const updateFontSize = (fontSize) => {
    setSettings(prev => ({ ...prev, fontSize }));
  };
  
  const updateNotification = (key, value) => {
    setSettings(prev => ({
      ...prev,
      notifications: {
        ...prev.notifications,
        [key]: value,
      },
    }));
  };
  
  return (
    <div className="settings-panel">
      <h2>Settings</h2>
      
      <section>
        <h3>Appearance</h3>
        <label>
          Theme:
          <select
            value={settings.theme}
            onChange={(e) => updateTheme(e.target.value)}
          >
            <option value="light">Light</option>
            <option value="dark">Dark</option>
            <option value="auto">Auto</option>
          </select>
        </label>
        
        <label>
          Font Size: {settings.fontSize}px
          <input
            type="range"
            min="12"
            max="24"
            value={settings.fontSize}
            onChange={(e) => updateFontSize(Number(e.target.value))}
          />
        </label>
      </section>
      
      <section>
        <h3>Notifications</h3>
        <label>
          <input
            type="checkbox"
            checked={settings.notifications.email}
            onChange={(e) => updateNotification('email', e.target.checked)}
          />
          Email Notifications
        </label>
        <label>
          <input
            type="checkbox"
            checked={settings.notifications.push}
            onChange={(e) => updateNotification('push', e.target.checked)}
          />
          Push Notifications
        </label>
      </section>
      
      <button onClick={resetSettings} className="reset-button">
        Reset All Settings
      </button>
    </div>
  );
}

总结 #

useResetRecoilState 的核心要点:

特点 说明
重置 将状态重置为默认值
无订阅 状态变化不会触发重渲染
性能 适用于只需要重置状态的组件
返回值 返回重置函数

下一步,让我们学习 useRecoilCallback,了解命令式访问状态的 Hook。

最后更新:2026-03-28