Graduate Program KB

React Hooks

  • Hook Rules
  1. Only use at top level of function
  2. Call hooks from function components or custom hooks
  3. Don't use hooks in conditions, loops or event handler
  • useState
    Used to manage component state in a functional component
const Counter = () => {
    const [count,setCount] = useState(0); //Default value for count is 0
    
    function increment(){
        setCount(count+1); //setCount updates count value
    }
    return (
        <div>
            <h2>{count}</h2>
            <button onClick={increment}>+</button>
        </div>
    )
}
  • useEffect
    Used to add side effects in a component. Side effects include fetching data or updating the DOM
const UserList = () => {
    const [users,setUsers] = useState([])
    useEffect(() => {
        async function fetchUSers() {
            const response = await fetch('ip/api/users'); //Gets data from API
            const data = await response.json(); //Turns resposne into json object
            setUsers(data)
        }
        fetchUsers();
    },[]); //2nd argument is empty, effect will only run once when component mounts
}
  • useReducer
    Used to store and update state, like useState. It accepts a reducer funtion and initial state
   const intialState = {count:0}
   
   const reducer123 = (state,action) => {
    switch (action.type) {
        case 'increment':
            return {count:state.count +1};
        default:
            throw new Error();
    }
   }

   const Counter = () => {
    const [state,dispatch] = useReducer(reducer123,intialState);
    function handleIncrement() {
        dispatch({type:'increment'});
    } //When handleIncrement is called, it will dispatch a type of command to the reducer.
    //In this case it will match the increment action and execute that
   }
  • useRef
    Used to access DOM directly or to persist values between renders
    const TextInput = () => {
        const [value,setValue] = useState('');
        const inputRef = useRef(null);

        function persistValue() {
            inputRef.current.value = "Persisting Value"
        }

        return (
            <div>
                <input ref={inputRef}/>
            </div>
        )
    }
  • useMemo
    Memoizes(Cache) the result of a function call, so it is not recalculated unless a state has changed.
    function computeValue(n) {
        return n * 1234
    }

    const Component = () => {
        const [number,setNumber] = useState(0);
        const memoValue = useMemo(() => computeValue(number),[number]);
        //memoValue won't get calculated until number has changed
    }

    function changeNumber(n){
        setNumber(n)
    }
  • useCallback
    Memoizes a function instead of the result. Function then won't be recreated after every render.
    const Component = () => {
        const [count,setCount] = useState(0);
        const increment = useCallback(() => {
            setCount(count +1)
        },[count])
        //increment is now a memoized function, and will be recreated when the [count] state has changed.
    }
  • useContext
    Allows a component to take in a context from a parent component. Context provides a way for react to pass data throughout the component tree.
import localeContext from './localeContext'

const Component = () => {
    const {data} = useContext(localeContext);
    //use data however
}
  • Custom Hooks
    You can create your own custom hook and share it across to multiple components. Usually has "use" prefix
    const useWhatever = (params) => {
        const [data,setData] = useState(params);
        const [data2,setData2] = useState(null);
        //Can include the built-in hooks uesEffect, etc
        return {data,data2}
    }

    const Component = () => {
        const {data,data2} = useWhatever("params")
    }