Hooks in React

Hooks help writing reusable code.

useState – Function that lets you use state in a functional component.

inside your functional component, deconstruct an array and pass in 2 values, first value will be a getter function and second value will be a setter, then call the useState function and pass in the initial value as a parameter.

const [term, setTerm] = useState("");

when you want to get the value, simply call term, when you want to set the value, simply use the setTerm() function.

useEffect – Function that lets you use something similar to lifecycle methods in functional components.

pass 2 arguments, first argument is what is going to happen, generally an empty arrow function, second argument is WHEN its going to happend.
No 2nd argument: initial render and every rerender, an empty array: only initial render, and array with value(s), initial and when the component rerenders and the data passed along in the array has CHANGED.

  useEffect(() => {
    console.log(searchTerm);
  }, [searchTerm]);

working with async and await when using useEffect.
simply create a small helper function inside of the function that is passed into useEffect that is asynchronous, then immediately after simply call the helper function.

  useEffect(() => {
    const search = async () => {
      await axios.get("");
    };
    search();
  }, [searchTerm]);

2nd method:

  useEffect(() => {
    //defines function and invokes immedietely
    (async () => {
      await axios.get("");
    })();
  }, [searchTerm]);

3rd approach is utilizing promises.


 useEffect(() => {
    axios.get("test")
    .then((response) => {
      console.log(response.data);
    });
  }, [searchTerm]);

clean up code with useEffect,
a return statement in the useEffect can ONLY return a function!
whats inside that function will be saved and triggered next time useEffect is being used!

example:

	useEffect(() => {
		const timeoutId = setTimeout(() => {
			//set the debouncedSearchTerm to the new searchTerm
			setDebouncedSearchTerm(searchTerm);
		}, 500);
		//whats in the return statement of the useEffect does not get triggered upon initial render
		// it will be saved in memory and invoked immedeitely upon next render, perfect for cleanup!
		return () => {
			//run this code NEXT time it gets rendered!
			clearTimeout(timeoutId);
		};
	}, [searchTerm]);

useRef – Function that lets you create a ref in a function component.

More predefined hooks:
useContext, useReducer, useCallback, useMemo, useImperativeHandle, useLayoutEffect, useDebugValue

Add your comment