Developer Tip of the Week: React Hooks

Developer Tip of the Week: React Hooks
Written by
Shedrack Akintayo
November 17, 2022
Tags
No items found.

React Hooks are in-built functions that allow React developers to use state and lifecycle methods inside functional components. And yes, they also work together with existing code.  Here are 5 React Hooks you should know:

useState()

The useState() Hook allows React developers to update, handle and manipulate state inside functional components. This is, probably, the most popular React Hook

Here's to use the useState() react hook:

function App() {
  const [age, setAge] = useState(19);
  const handleClick = () => setAge(age + 1)

  return
      <div>
          I am {age} Years Old
        <div>
        <button onClick={handleClick}>Increase my age! </button>
      </div>
   </div>
}


useEffect()

The useEffect() hook accepts a function that would contain effectual code, like mutations, subscriptions, timers, logging etc. This is probably the most controversial React Hook 😉 

Here's how to use the useEffect() React Hook:

function App() {
  const [age, setAge] = useState(19);
  const handleClick = () => setAge(age + 1)
   useEffect(() => {
    // Update the document title using the browser API
    document.title = `You are ${age} years old` ;
  });

  return
      <div>
          I am {age} Years old
        <div>
        <button onClick={handleClick}>Increase my age! </button>
      </div>
   </div>
}

useRef()

The useRef() Hook returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).

Here's how to use the useRef() React Hook:

const refContainer =useRef(initialValue);

useContext()

The useContext() Hook gives functional components easy access to the React app context.

Here's how to use the useContext() react hook:

const value = useContext(MyContext);

useLayoutEffect()

The useLayoutEffect() Hook is similar to  useEffect(), however, it fires synchronously after all DOM mutations, so timing is important.

Here's how to use the useLayoutEffect() React Hook:

useLayoutEffect(() => {
      // do side effects
     return () => /* cleanup */
}, [dependency, array]);