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(() => {
  }, [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("");
  }, [searchTerm]);

2nd method:

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

3rd approach is utilizing promises.

 useEffect(() => {
    .then((response) => {
  }, [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!


	useEffect(() => {
		const timeoutId = setTimeout(() => {
			//set the debouncedSearchTerm to the new 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!
	}, [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