博客 / 詳情

返回

什麼時候不應該使用useEffect?

當你的數據是同步的

差的:
數據來源是同步的,沒有必要使用。

function App() {
  const [todos, setTodos] = useState([]);
    
  useEffect(() => {
    const str = localStorage.getItem('todos');
    const items = JSON.parse(str) || [];
    setTodos(items);
  }, []);

  return (
    <>
      {todos.map((item) => (
        <>{item}</>
      ))}
    </>
  );
}

正確示例:
直接使用。

function App() {
  const str = localStorage.getItem('todos');
  const items = JSON.parse(str) || [];
  const [todos, setTodos] = useState(items);

  return (
    <>
      {todos.map((item) => (
        <>{item}</>
      ))}
    </>
  );
}

當你的數據可以通過其他數據計算得來

差的:

const TOPICS = [
  {
    id: 1,
    name: 'name-1',
  },
  {
    id: 2,
    name: 'name-2',
  },
  {
    id: 3,
    name: 'name-3',
  },
];

function Topic({ selectTopicId }) {
  const [selectedTopIC, setSelectedTopic] = useState(null);

  useEffect(() => {
    const targetItem = TOPICS.find((item) => item.id === selectTopicId);
    setSelectedTopic(targetItem);
  }, [selectTopicId]);

  return (
    <>
      <div>selectedTopic: {selectedTopic}</div>
    </>
  );
}

更好的:
從已有數據中派生。

const TOPICS = [
  {
    id: 1,
    name: 'name-1',
  },
  {
    id: 2,
    name: 'name-2',
  },
  {
    id: 3,
    name: 'name-3',
  },
];

function Topic({ selectTopicId }) {
  const selectedTopic = TOPICS.find((item) => item.id === selectTopicId);

  return (
    <>
      <div>selectedTopic: {selectedTopic}</div>
    </>
  );
}
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.