
What is React Hooks
Requirements
- React.js (16.8 or newer)
Introduction
Hooks are the functions which "hook into" React state and lifecycle features from function components. It does not work inside classes. Before hooks when you would want to add state to your React functional component, you would do it by transforming it in a class component.
State Hook
is the state management hook we call inside a functional component to add local state to it. The state will be preserved between re-renders.
returns two things: the current state and a function that lets you update it.
accepts one argument and it is the initial state.
Here a example of how it works:
import React, { useState } from "react"; function StateExample() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }
Effect Hook
Operations like data fetching, subscriptions, and manually changing the DOM from React components are called "side effects", because they can affect other components and can't be done during rendering.
hook adds the ability to perform side effects from a functional component.
When you call , you’re telling React to run your “effect” function after performing changes to the DOM. The example below shows how it acts after we update state:
import React, { useState, useEffect } from "react"; function EffectExample() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }
Rules of Hooks
Hooks are essentially javaScript functions, but to use them properly there are two additional rules:
- Only call hooks at the top level. Don't call hooks inside loops, conditions, or nested functions.
- Only call hooks from React function components.
Building Custom Hooks
Let's say we want to create a custom hook that identifies whether some element is hovered
import React, { useState, useRef, useEffect } from "react"; // Component function App() { const [hoverRef, hovered] = useHover(); return ( <div ref={hoverRef} style={{ color: hovered ? "blue" : "#2d2d2d" }}> <h1>Hover Here</h1> </div> ); } // Hover Hook function useHover() { const [value, setValue] = useState(false); const ref = useRef(null); const handleMouseOver = () => setValue(true); const handleMouseOut = () => setValue(false); useEffect(() => { const element = ref.current; if (element) { element.addEventListener("mouseover", handleMouseOver); element.addEventListener("mouseout", handleMouseOut); return () => { element.removeEventListener("mouseover", handleMouseOver); element.removeEventListener("mouseout", handleMouseOut); }; } }, []); return [ref, value]; } export default App;
Additional Resources
Related Posts
- Data fetching in React.js / Next.js2023-01-08
- What is React Hooks2021-08-25
- How to make a scroll to the top button in React2021-01-16