useState
function App() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>{count}</button>
)
}
useEffect
模拟componentDidMount&componentDidUpdate
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `你点击了${count}次`
});
return (
<button onClick={() => setCount(count + 1)}>{count}</button>
)
}
模拟componentWillUnmount
useEffect(() => {
return () => {
console.log('unmount')
}
});
模拟componentDidMount
useEffect(() => {
console.log('component did mount')
}, []);
模拟shouldComponentUpdate
function App() {
const [count, setCount] = useState(0);
const [day, setDay] = useState(1);
useEffect(() => {
console.log('day change')
}, [day]);
return (
<div>
<button onClick={() => setCount(count + 1)}>{count}</button>
<button onClick={() => setDay(day + 1)}>update day</button>
</div>
)
}
useContext
const myContext = React.createContext()
function App() {
return (
<myContext.Provider value={{ age: 1, name: "zj" }}>
<Child />
</myContext.Provider>
)
}
function Child() {
const childContext = useContext(myContext)
return (
<>
<h1>{childContext.name} is {childContext.age} year old</h1>
</>
)
}
useReducer
const initialState = { count: 0 }
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 }
break;
case 'decrement':
return { count: state.count - 1 }
break;
default:
break;
}
}
function App() {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<div>
<h1>{state.count}</h1>
<button onClick={() => dispatch({ type: 'increment' })}>+1</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-1</button>
</div>
)
}
useCallback
const set = new Set()
function App() {
const [count, setCount] = useState(1);
const [val, setVal] = useState('');
const callback = useCallback(() => {
console.log(count);
}, [count]);
set.add(callback)
return <div>
<h4>{count}</h4>
<h4>{set.size}</h4>
<div>
<button onClick={() => setCount(count + 1)}>+</button>
<input value={val} onChange={event => setVal(event.target.value)} />
</div>
</div>;
}
useRef
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` 指向已挂载到 DOM 上的文本输入元素
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}