useEffect Hook#

The useEffect hook is called on specific external events. For example the useEffect hook is called after the component is rendered. We can use this hook to do additional calls. In our case we want to fetch the initial data from the backend.

29  useEffect(() => {
30    dispatch(getFaqItems());
31  }, [dispatch]);

The getFaqItems method is called using the dispatch hook. The full Faq component will now look like this:

 1import { useState, useEffect } from "react";
 2import { useSelector, useDispatch } from "react-redux";
 3
 4import { addFaqItem, getFaqItems } from "../actions";
 5import FaqItem from "./FaqItem";
 6
 7function Faq() {
 8  const faqList = useSelector((state) => state.faq);
 9  const dispatch = useDispatch();
10
11  const [question, setQuestion] = useState("");
12  const [answer, setAnswer] = useState("");
13
14  const onChangeAnswer = (e) => {
15    setAnswer(e.target.value);
16  };
17
18  const onChangeQuestion = (e) => {
19    setQuestion(e.target.value);
20  };
21
22  const onSubmit = (e) => {
23    e.preventDefault();
24    setQuestion("");
25    dispatch(addFaqItem(question, answer));
26    setAnswer("");
27  };
28
29  useEffect(() => {
30    dispatch(getFaqItems());
31  }, [dispatch]);
32
33  return (
34    <div>
35      <ul>
36        {faqList.map((item, index) => (
37          <FaqItem
38            key={index}
39            question={item.question}
40            answer={item.answer}
41            index={index}
42          />
43        ))}
44      </ul>
45      <form onSubmit={onSubmit}>
46        <label>
47          Question:{" "}
48          <input
49            name="question"
50            type="text"
51            value={question}
52            onChange={onChangeQuestion}
53          />
54        </label>
55        <label>
56          Answer:{" "}
57          <textarea name="answer" value={answer} onChange={onChangeAnswer} />
58        </label>
59        <input type="submit" value="Add" />
60      </form>
61    </div>
62  );
63}
64
65export default Faq;
Differences
-import { useState } from "react";
+import { useState, useEffect } from "react";
 import { useSelector, useDispatch } from "react-redux";

-import { addFaqItem } from "../actions";
+import { addFaqItem, getFaqItems } from "../actions";
 import FaqItem from "./FaqItem";

 function Faq() {
@@ -26,6 +26,10 @@ function Faq() {
     setAnswer("");
   };

+  useEffect(() => {
+    dispatch(getFaqItems());
+  }, [dispatch]);
+
   return (
     <div>
       <ul>