Learn React Custom Hooks (with screencast)

Harry Anderson
EPFL Extension School
2 min readMay 21, 2019

With version 16.8, React unveiled a new set of functions that can help us make our React components less verbose, and more modular. But Hooks can be confusing for many developers who are used to working with class-based components.

And to many people, it isn’t clear why we need hooks. To these people, React has become overly-complicated, with new features and patterns of development emerging every few months.

Hooks can help though. And I promise that they aren't difficult to learn. In fact, they are much easier to understand than render-props or higher-order components, and if you watch the tutorial below you'll see why.

A screenshot of the component that we'll create in the tutorial below.

The video focuses on Custom Hooks, which is a new way of creating function components that can help to de-clutter your virtual DOM. Using custom hooks, you can build React components that don't need complex wrappers to manage their state — a consequence of innovative patterns like higher-order components and render-props.

A component should look and behave like a modular piece of a user-interface — without complex wrappers. And the Virtual DOM should be easy to debug and navigate. In the tutorial below, I demonstrate how to build a block-quote component that uses a custom hook.

Watch the tutorial —you'll learn how to use hooks!

Thanks for watching! You can find the code from the video below, and if you want to learn more about React hooks, consider taking my course with the EPFL Extension School.

function useTimedItem(items) {
const [activeItem, setActiveItem] = useState(0);
const interval = window.setInterval(() => {
if (activeItem < items.length - 1) {
setActiveItem(activeItem + 1);
} else {
setActiveItem(0);
}
}, 3000);
useEffect(() => () => clearInterval(interval)); return items[activeItem];
}
function BlockQuote({ author, citation, picture, quote }) {
return (
<blockquote cite={citation}>
<img src={picture} alt="Portrait" />
<div>
<p>
<q>{quote()}</q>
</p>
<footer>{author}</footer>
</div>
</blockquote>
);
}
ReactDOM.render(
<BlockQuote
author="Jean-Luc Picard"
citation="https://en.wikiquote.org/wiki/Jean-Luc_Picard"
picture="https://upload.wikimedia.org/wikipedia/commons/2/2e/Jean-Luc_Picard_2.jpg"
quote={() => useTimedItem([
"There are four lights!",
"Tea. Earl Grey. Hot."
])}
/>,
document.getElementById("root")
);

About the EPFL Extension School

The EPFL Extension School teaches digital skills in data science, machine learning, web application development, UI Development with React.js, and more. Please visit our website, reach out to us by e-mail or Twitter, listen to Harry’s podcast on React here, and most importantly: go get those digital skills!

--

--