Hooks are functions that let you “hook into” React state and lifecycle features from function components.
-
useState
- deconstruct/define? value name and update function
const [name, updateName] = useState('Greg')
- each time you use a
useState
hook, it isolates its own state- extracting an update state call into a reusable generic function works to define separate states
-
useContext
- deconstruct/use values from React context
const [theme, updateTheme] = useContext(ThemeContext)
-
useEffect
- essentially lifecycle methods replacement
- ComponentDidUpdate often needed to ensure proper re-rendering with updates...forgetting to handle componentDidUpdate properly is a common source of bugs in React applications.
- You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect (instead of === comparison for everything)
-
useRef
-
useReducer
- Whaaaaat?!
- You cannot use hooks inside of a conditional, have to be declared at top level
- Using react hooks to extract pieces of a functional component
- Always start with "use" to mirror react hooks syntax
Notes:
- Hooks don’t replace your knowledge of React concepts. Instead, Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. As we will show later, Hooks also offer a new powerful way to combine them
- Shared state between components is hard. With hooks you can create custom hooks and share state amongst multiple components easier than HOC's or render props
- Classes present issues for today’s tools. For example, classes don’t minify very well, and they make hot reloading flaky and unreliable.
- Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution.