Hooks are simply functions that allow us to add lifecycle features and states to functional components.
Rules of Hook
There are two rules that must be followed when working with Hooks
Hooks should always be called at the top level. Hooks should not be called inside loops, conditions, or nested functions. This is to ensure that after every render of the components, the Hooks are called in the same order every time.
Hooks can only be called from React functions. Hooks cannot be called from regular JavaScript functions. Therefore, they can be called from functional components and from custom Hooks.
Basic Hooks
useState
const [state, setState] = useState(initialState);
This hook is used to add states to functional components. Using the initialState argument, we can provide an initial state if needed. The hook returns the current state and a function that is used to update the state. If the state is updated, the component is re-rendered.
For naming the state and its updating function, the common convention that is followed is [something, setSomething].
useEffect
This hook is used to perform side functions in the components, such as fetching data, subscription set up etc. It is used to make the component do something right after rendering. It runs after every render by default.
useEffect(()=> {
// some code }, [])
The optional second argument is so that the component re-renders only if the value of that argument has changed.
useContext
This hook is useful in avoiding prop drilling as it allows to manage states globally. The components can be re-rendered when these global states change.
First, the context has to be created and initialized. Then the child components have to be wrapped in the Context Provider and the state value has to be supplied.
const UserContext = createContext()
function Component1() {
const [user, setUser] = useState("Jesse Hall");
return (
<UserContext.Provider value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 user={user} />
</UserContext.Provider>
);
}
After this, the user Context will be accessible in all the components.
Custom Hooks
React also gives us the option to create our own hooks according to our needs. We may need custom hooks when we have a reusable function. The custom Hook’s name must start with “use”. Example: useStatus.
Top comments (0)