Home >Web Front-end >JS Tutorial >React Hooks
React Hooks are functions that allow you to use state and other React features in functional components, which traditionally were only available in class components. They were introduced in React 16.8 and have since become a standard for writing React components. Here's a breakdown of the most commonly used hooks:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); // Declare a state variable called 'count' return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
import React, { useEffect, useState } from 'react'; function Example() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); // Empty dependency array means this effect runs once after the initial render. return <div>{data ? data : 'Loading...'}</div>; }
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); function DisplayTheme() { const theme = useContext(ThemeContext); // Access the current theme context value return <div>The current theme is {theme}</div>; }
import React, { useReducer } from 'react'; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } } function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>+</button> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> </div> ); }
import React, { useRef, useEffect } from 'react'; function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { inputEl.current.focus(); // Access the DOM element directly }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
import React, { useMemo, useCallback } from 'react'; function Example({ items }) { const expensiveCalculation = useMemo(() => { return items.reduce((a, b) => a + b, 0); }, [items]); const memoizedCallback = useCallback(() => { console.log('This function is memoized'); }, []); return <div>{expensiveCalculation}</div>; }
Hooks have transformed the way developers write React applications, making functional components more capable and easier to manage.
The above is the detailed content of React Hooks. For more information, please follow other related articles on the PHP Chinese website!