Hooks 🎣
Hooks are functions that give you React features like state and lifecycle methods without classes
Hooks to replace higher-order components and render props.
Hooks make it easier to reuse stateful logic.
Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods.
Hooks are functions that let you “hook into” React state and lifecycle features from function components.
Hooks don’t work inside classes — they let you use React without classes.
Basically you can hook them whenever you want so you don't want to follow the conventional lifecycles. You can hook and unhook your code in your function. The code is cleaner this way.
Each call to a Hook has a completely isolated state — so you can even use the same custom Hook twice in one component.
State Hook useState
useState
Call it inside a function component to add some local state to it
useState
returns a pair: the current state value and a function that lets you update it.
Context Hook useContext
useContext
Accepts a context object and returns the current context value for that context
useContext
lets you subscribe to React context without introducing nesting
Reducer Hook useReducer
useReducer
useReducer
lets you manage local state of complex components with a reducer
Effect Hook useEffect
useEffect
It adds the ability to perform side effects from a function component
Mainly used for data fetching, subscriptions, or manually changing the DOM from React components
They are side effects because they can affect other components and can’t be done during rendering.
It serves the same purpose as
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
in React classes, but unified into a single API.Hooks let you organize side effects in a component by what pieces are related (such as adding and removing a subscription), rather than forcing a split based on lifecycle methods.
Last updated