[React] Using key prop to reset component to avoid useEffect hook

The component using useEffect which is not necessary:

function TopicEditor({ selectedTopicId }) {
    const [enteredNote, setEnteredNote] = useState('');
    const selectedTopic = DUMMY_TOPICS.find(topic => topic.id === selectedTopicId)
    
    useEffect(() => {
         if (selectedTopic) {
             setEnteredNOte(selectedTopic.note)
         }
    }, [selectedTopic]);
    
    return (
      ....
    )
}

function App() {
    const [selectedTopicId, setSelectedTopicId] = useState();
    return (
        <TopicEditor selectedTopicId={selectedTopicId} />
    )
}

 

The way we can get rid of useEffect from the TopicEditor component is passing a key prop to it, so everytime when key changes, the TopicEditor component will be reset.

function App() {
    const [selectedTopicId, setSelectedTopicId] = useState();
    return (
        <TopicEditor key={selectedTopicId} selectedTopicId={selectedTopicId} />
    )
}

 

function TopicEditor({ selectedTopicId }) {
    const selectedTopic = DUMMY_TOPICS.find(topic => topic.id === selectedTopicId)    
    const [enteredNote, setEnteredNote] = useState(selectedTopic?.note);

    // useEffect(() => {
    //     if (selectedTopic) {
    //         setEnteredNOte(selectedTopic.note)
    //     }
    // }, [selectedTopic]);
    
    return (
      ....
    )
}

 

posted @ 2024-04-08 14:49  Zhentiw  阅读(1)  评论(0编辑  收藏  举报