Purpose: To learn to use the useState, useEffect, useRef, and useLocation "hook" functions in React.
Before 2019, functional components existed but were meant to be presentational only, not smart like class components. Only class components were able to hold state variables and run event-driven lifecycle methods. In 2019, methods like useState and useEffect were added, making functional components just as flexible as class components. They were called "hook" methods because they "hook into" the state and lifecycle features of React. Since the introduction of hooks, functional components became the most popular way to code React. In this exercise, we will learn to use useState, useEffect, useRef, and useLocation, which will all be important in the project.
Hook functions need to be imported into code where used:
The above import loads all hook functions we will use in this exercise. In your files, import only what is needed. Note that 'react' needs to be lower case (using upper case makes bizarre errors).
The useState function enables functional components emulate state variables in class components, though the mechanism differs. The syntax of useState is:
The useState function returns an array with a variable (varName, initialized to value) and a function (setVarName). React keeps track of the variable's value when the component is destroyed and re-initialized. Several actions in React can trigger a component being destroyed and re-initialized. Calling the set function (setVarName in this example) is one of them. The variable (varName) is a const because it never actually changes until the component is destroyed and the function re-runs.
Change Contact.jsx so it uses a state variable to render the form from Exercise 4.2 if the user clicks a link. As in the example below, split the content into components, and use conditional rendering. For now, do not worry about making the form submit properly (no "action" attribute below). Note that in the example below, the CSS specific to the BatForm from Exercise 4.2 is added using an imported CSS file, which makes that CSS conveniently come into existence when BatForm is mounted and out of existence when it is unmounted.
The useEffect function enables functional components to emulate componentDidMount(), componentDidUpdate(), and componentWillUmount(), which are "lifecycle methods" in class components. Three separate parts of the function do this. The syntax is:
Although useEffect takes only two parameters, it allows you to create up to three listeners, emulating the class component lifecycle functions componentDidMount, componentWillUnmount, and componentDidUpdate. Pay careful attention to the arguments passed into useEffect as you run the code below:
The Mount Listener is the setupFunction argument. See explanation below.
The Unmount Listener is returned by setupFunction. See explanation below.
The updateTriggers array adds an Update Listener. See explanation below.
The Mount Listener is setupFunction, the First Argument. In the first example above, setupFunction is an anonymous function (one that changes the background). To test, click on the About link in the nav, which renders the <About> component. The background turns black and stays black, because useEffect is called when the <About> component is mounted.
The Unmount Listener is setupFunction's return function. In the second example above, setupFunction now has a return value (an anonymous function that reverts the background). To test, click on the About link, then click on any other link in the nav. The background turns black when About is mounted, but clicking on another link causes it to unmount. When this happens setupFunction's return function is called, reverting the background. People call this return function the "cleanup" function.
The Update Listener is controlled by updateTriggers. Look carefully to see that useEffect has two arguments, an anonymous function and an array (updateTriggers). In the first and second example above, updateTriggers is the empty array, []. The third example adds an update listener by putting a state variable into updateTriggers, [clicks]. People call updateTriggers the "dependency array." To test, click on the About link, then click on the text "I'm Batman" 5 times, and it should alert a silly message. Look at the way the state variable is created. Look at the click handler in the component. Understand that useEffect is called each time any state variable in updateTriggers changes.
The useRef function creates variables that do NOT force components to re-render but DO persist when components re-render. Among other things, useRef can be used to point to an HTML element. The syntax is:
or, when value is not important, such as when useRef is being used to point to an element:
and the HTML element is tied to it using an attribute called "ref", as follows:
Among other things, useRef can be used to point to an HTML element, as shown in the example below, which makes a form auto-focus. When using useRef, always modify useRef.current, because const objects have mutable attributes.
The useRef function is very handy for styling file inputs, which are notoriously hard to style with CSS, by hiding them and using another object simulate clicking on them, as shown in the example below:
You may already have noticed that in React, event listeners require camelCase capitalization (onClick instead of onclick, onSubmit instead of onsubmit), and that they always take a function as value, never a string like in HTML. It is also helpful to know that some of them behave differently. Most notably, in a form, the onChange listener in React fires with every keypress instead of only when the element is defocused. Finally, React uses its own event object (see short article on React events) for browser consistency and added functionality. Run and study the example below, where an onChange event is added to the file input. In conjunction with an additional state variable, it shows a file preview inside the file button before the file is uploaded.