Front-end team lead
Oslo Market Solutions
espen_dev
esphen
An introduction
// 🔴 We're breaking the first rule by using a Hook in a condition
if (name !== '') {
useEffect(function persistForm() {
localStorage.setItem('formData', name);
});
}
useEffect(function persistForm() {
// 👍 We're not breaking the first rule anymore
if (name !== '') {
localStorage.setItem('formData', name);
}
});
const [state, setState] = useState(initialState);
useEffect(didUpdate, shouldUpdateFor);
// Example
useEffect(() => {
setInterval(doSomething, interval);
return () => {
clearInterval(doSomething);
};
}, [interval])
const contextValue = useContext(Context);
const [state, dispatch] = useReducer(reducer, initialArg, init);
// Example
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
);
}
// Returns a memoized callback
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);
// Returns a memoized value
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const refContainer = useRef(initialValue);
useDebugValue(value);
// Example
// Show a label in DevTools next to this Hook
// e.g. "FriendStatus: Online"
useDebugValue(isOnline ? 'Online' : 'Offline');
https://slides.com/esphen/hooks