React Hook
This writing provides an overview and introduction of React Hook.
1. What is a Hook?
- Hooks allow function components to access React state and lifecycle features.
- Rules for using hooks:
- Only call hooks at the top level of your component.
- Only call hooks within React function components or custom hooks.
import React, { useState, useEffect } from 'react'; function TitleCount() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); return <button onClick={(prev) => setCount(prev + 1)}>+</button>; }
2. useState() Hook
- The
useState
hook allows adding state to function components.
- It should be called at the top level of a component to manage its state.
- When
useState
is called, it returns an array with two values: currentState
: The current state value.stateSetter
: A function to update the state.- initialState: Initial value. true, false or some value etc.
import React, { useState } from 'react'; function ExampleComponent() { const [currentState, stateSetter] = useState("initialState");
- These values are usually assigned to local variables using array destructuring.
- Example usage:
import React, { useState } from 'react'; function Toggle() { const [toggle, setToggle] = useState(); return ( <div> <p>The toggle is {toggle}</p> <button onClick={() => setToggle("On")}>On</button> <button onClick={() => setToggle("Off")}>Off</button> </div> ); }
- On the above example, there is no initialState, so it would be undefined at first rendering.
- If the next state depends on the previous state, use a callback function with
stateSetter
:
function Counter({ initialCount }) { const [count, setCount] = useState(initialCount); return ( <div> Count: {count} <button onClick={() => setCount(initialCount)}>Reset</button> <button onClick={() => setCount((prevCount) => prevCount - 1)}>-</button> <button onClick={() => setCount((prevCount) => prevCount + 1)}>+</button> </div> ); }
- Multiple
useState
hooks can be used within a single component.
function App() { const [sport, setSport] = useState('basketball'); const [points, setPoints] = useState(31); const [hobbies, setHobbies] = useState([]); }
3. useEffect() Hook
- The
useEffect
hook lets a component perform actions when it is rendered or re-rendered. - It can be used for side effects such as data fetching, subscriptions, or manually changing the DOM.
- Example usage:
useEffect(() => { // Function to be performed }, [dependencies]);
3-1. Effect Cleanup Functions:
- Sometimes, cleanup functions are necessary within
useEffect
to prevent memory leaks or unwanted behavior. - For example, removing an event listener that was added in the effect:
useEffect(() => { const handleEvent = () => { /* ... */ }; window.addEventListener('resize', handleEvent); return () => { window.removeEventListener('resize', handleEvent); }; }, []);
3-2. Dependencies
- The
useEffect
hook takes a callback function and a dependency array. - If no dependency array is provided, the effect runs after every render.
useEffect(() => { alert('called after every render'); });
- An empty dependency array (
[]
) makes the effect run only once after the initial render.
useEffect(() => { alert('called after first render'); }, []);
- If the dependency array contains values, the effect runs only when any of those values change.
useEffect(() => { alert('called when value of `endpoint` or `id` changes'); }, [endpoint, id]);
Other than useState, useEffect, there are many other built-in hooks like useRef etc. For another hooks please refer to React documents or other web.
Comments
Post a Comment