Chenyo's org-static-blog

23 Jun 2024

Weblab notes: React hooks

This is a personal note for the web.lab lectures.

1. What is a React hook

  • Special functions to access parts of the component lifestyle.
  • e.g., useState

1.1. useState is not enough

1: const [persons, setPersons] = useState([]);
2: 
3: testingStuff = () => {
4:     /* assume persons is empty before */
5:     setPersons([...persons, "me"]);
6: }
7: console.log(persons);
  • The output of console.log is [] instead of ["me"] because setting a state is async!
  • To do something immediately after a state is changed, use useEffect hook!

1.2. useEffect runs after specific variable change

1: useEffect(() => {
2:     console.log(persons);
3: }, [persons]);
1: useEffect(() => {
2: /* do something, e.g., interact with an external service */
3: 
4: return () => {
5: /* cleanup function on dismount, e.g., disconnect from external service */
6: }
7: }, [/*dependencies */])
  • useEffect(myFunction, [var1, var2]) calls myFunction everytime when var1 or var2 changes
  • useEffect(myFunction, []]) calls only once when the component is rendered for the first time (on mount)
  • useEffect(myFunction) calls at every render

2. React hook patterns

2.1. Fetch and send data

1: /* fetch data on mount */
2: useEffect(() => {
3:     get("/api/packages").then((packageList) => {
4:         setPackages(packageList);
5:     });
6: }, []);
1: /* send data then toggle admin state */
2: const handleToggleAdmin = () => {
3:     // .then(), do something once the promise is fulfilled
4:     post("/api/user/admin", { admin: !admin }).then(() => {
5:         setAdmin(!admin);
6:     });
7: };
8: /* <Button onClick={handleToggleAdmin} */

2.2. Conditional rendering

1: // JSX is a way of writing HTML in js
2: let content = loading ? <p>Loading...</p> : <p>Loaded</p>;
3: return (
4:     <div>
5:         <h1>Title</h1>
6:         {content}
7:     </div>
8: );

2.3. Render an array of Data

1: const data = [
2:     { id: 0, text: "Text 1" },
3:     { id: 1, text: "Text 2" },
4: ];
5: // render a component for each data item
6: return data.map((item) => (
7:     <ItemComponent key={item.id}>{item.text}</ItemComponent>
8: ));
  • key is a special prop in React; it is used identify which item has changed efficiently

3. Example: Stopwatch

 1: const Stopwatch = () => {
 2:     const [time, setTimer] = useState(0);
 3: 
 4:     useEffect(() => {
 5:         const timer = setInterval(() => {
 6:             // setTimer accepts either a new state value,
 7:             // or a function that takes the previous state (oldTime) as an argument and returns the new state
 8:             setTime((oldTime) => oldTime + 1);}, 1000);
 9:         // if not properly cleanup after unmounting
10:         // the timer will continue to run even the state no longer exists
11:         return () => clearInterval(timer);
12:     }, []);
13:     return <>TIme: {time}</>;
14: };

4. DOM and component mounting

  • DOM (Document Object Model): a programming interface for web documents; represents the structure of a document, e.g., HTML, as a tree of objects, where each object corresponds to a part of the document; it dynamically updates the document contents
    • React is a framework that manipulates DOM
  • A React component is unmounted when:
    • conditional rendering
    • routing; navigating from one route to another
    • its parent component is unmounted
Tags: study web react mit