17. 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            question={item.question}
39            answer={item.answer}
40            index={index}
41          />
42        ))}
43      </ul>
44      <form onSubmit={onSubmit}>
45        <label>
46          Question:{" "}
47          <input
48            name="question"
49            type="text"
50            value={question}
51            onChange={onChangeQuestion}
52          />
53        </label>
54        <label>
55          Answer:{" "}
56          <textarea name="answer" value={answer} onChange={onChangeAnswer} />
57        </label>
58        <input type="submit" value="Add" />
59      </form>
60    </div>
61  );
62}
63
64export 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>