DEV Community

Cover image for React Hooks in action
Terry Threatt
Terry Threatt

Posted on

React Hooks in action

React Hooks

If you have been developing in React since early 2019, you may have heard React Hooks or perhaps seen some hooks out in the wild in some codebases you have worked on. If not! here is a quick crash course on React Hooks. The React Hooks API was added to the React 16.8 release a few years ago. Introducing a new way of bringing the state to a functional component. As you may know state on lived in React class components prior to this release.

Hooks in Action

Let's take a quick look at the two most common React Hooks that you may see in a React project.

import React, { useState } from 'react'; 

function Game() { 
// This allows us to create state and refer to our state object "score" 
const [score, setScore] = useState(0); // I can set some default state as a argument of any datatype

return (
<div>
  <p>Here is the total {score} of the game</p> 
  <button onClick={() => setScore(score + 1)}>Update Score</button> // Here we click a button to increment the state 'score' and trigger a rerender. 
</div>
);
}

Enter fullscreen mode Exit fullscreen mode
 import React, { useState, useEffect } from 'react'; 

function Game() { 
const [score, setScore] = useState(0); 

   useEffect(() => {
     document.title = Current Score {score} // the useEffect is a great hook to update any side-effect each time a re-render happens. 
}

)
return (
<div>
  <p>Here is the total {score} of the game</p> // refers to state value 
  <button onClick={() => setScore(score + 1)}>Update Score</button> // Here we click a button to increment the state 'score'
</div>
);
}


Enter fullscreen mode Exit fullscreen mode

Need for hooks

According to the React team, hooks emerged as the projects became very difficult to reuse stateful logic into many different components without the help from several patterns like render props and higher-order components. Hooks give an opportunity to simplify stateful logic by not relying on any complex class components and making it super easy to split up code into more meaningful functions.

Let's chat about hooks

So now you have more than a few things about how to use hooks in React. If you enjoyed this post feel free to leave a comment about your thoughts and experiences working with React hooks.

Happy Coding,
Terry Threatt

Discussion (0)