ScanSkill

React Hooks

React hooks allows us to use the features of a class component like state and lifecycles in a functional component. We can import the hooks from react to use them.

We need to follow these rules when using them:

  • Hooks can only be called at the top level of a component. Do not call Hooks inside loops, conditions, or nested functions.
  • Hooks can only be called inside React function components or custom Hooks. We cannot call Hooks from regular JavaScript functions.
  • Hooks cannot be conditional

The built-in Hooks can be divided into two parts:

Basic Hooks

  • useState
  • useEffect
  • useContext

Additional Hooks

  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

We can also create our custom hooks. A custom Hook is just like a regular function that starts with "use" and can call other Hooks. It follows the rules of Hooks.

Example

Here is a simple counter app that uses useState to manage the state.

import React, {useState} from 'react'        //import the hook

function Example() { 
  const [value, setValue] = useState(0)      //initialize useState

  const handleDecrement = () => {
    setValue(value - 1);                     // modify state             
  }

  const handleIncrement = () => {
    setValue(value + 1)                      //modify state
  }

  return (
    <div>
      <button onClick={handleDecrement}>-</button>
      <span>{value}</span>                          // read state
      <button onClick={handleIncrement}>+</button>
    </div>
  )
}

export default Example