In this article we'll discuss about React Hooks. Before the release of React Hooks, its functional components were a bit limited in usage. I mean, when it comes to working with State, context API, and some Lifecycle methods there was nothing we could do.
But, starting from React 16.8, we have a lot more flexibility to reuse an existing piece of code.
✨Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which "hook into" React state and lifecycle features from function components.
✨ Hooks don't work inside class components. They let you use React without the class.
✨ Hooks will reduce your component size significantly and have many other benefits.
You can use hooks only inside a function components. Not inside class components because classes already have features what hooks enable you to do.
You should call hooks only at the Top Level of the function. Don't call Hooks inside loops, conditions, or nested functions.
There is just one other valid place to call Hooks is your Custom Hooks.
Let's get Started with the top most great React Hooks.🔥
⚡ 1. useState( ) Hook:
👉 The useState( ) hook lets you add react state to function components. So function components are no longer stateless.
👉 The useState( ) is the most commonly used Hook that allows you to create, read and update simple internal state variables in your react function component.
Sounds great right, Stay tuned then.😎
🤷♂️ Why useState( ) is not named as createState( ) ?🤔
👉 Create would imply that the state was created for the first time when the component renders. But the useState( ) executes every time the function component re-renders.
👉 During the subsequent re-renders, the useState( ) hook will give us the Current State.
👉 So "use"State( ) is appropriate name.
Let's look at the syntax of useState( ):
👉 useState hook always returns an array with 2 values.
- The State variable itself.
- A function to update the state variable.
👉 If you use this state variable inside JSX, the component re-renders every time the value changes.
👉 The setVariable function is used to update the state variable whenever needed in the component.
👉 The "setVariable" name doesn't really matter. You can name it anything you want.
Let's look at few examples of the useState( ):
⚡ 2. useEffect( ) Hook:
👉 The Effect Hook lets you perform side effects in function components. If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
👉 It is like a Functional programming concept, where we try to encapsulate side effects in other functions so that other Functions can stay pure/unaffected.
👉 useEffect hook must declare inside the component (top-level, don't declare them in the block), it will give several advantages (Thanks to closure):
It will have accessibility to those data that are required to use in side effects.
It can also update the data later, based on the dependencies and changes.
- The first argument in useEffect is to give side effects function.
- The second argument is the dependencies array which gives instructions to useEffect hook when to run and when to not. Let's see this more closely:
- If you don't give dependences array, only pass the first argument, then useEffect runs whenever your component renders/re-renders.
- If you give an empty dependences array, then useEffect runs once(when your component renders the first time, after that, it will not run unless you refresh the page).
- If you give something in the dependencies array, then useEffect will run once by default after the component finish rendering. After that, whenever the value of elements in the dependences array change, then useEffect will run again. Example: [isItemHidden].
👉 Well, whenever your components finish rendering, useEffects run unless you specified dependencies in the dependencies array.
🤷♂️ Why should we use useEffects( )? 🤔
There are several cases where you should consider useEffects. Some of them are:
Suppose you are fetching some data online to display movie titles, ratings & you have used handler(Function with the synthetic event) or used inline Functions to get that data. So, what will happen is your component rendering will be stuck when the thread of execution reaches this point until you get the data from outside of the world.
By seeing the first point, we can move those side effects to the useEffect hook so that our components can load/render. After completing the rendering process, React Engine will fire the useEffect hook to run the side effects code and update the component data.
We should useEffect, when your component depends on the outside world data, and we can not guarantee that data will come or not (maybe the server is down there). So, Instead of throwing errors and stop other components from being rendered, move them into useEffect hook.
When you are using browser API (including Timer function, fetch API, local storage and for more browser API, refer to this: MDN Browser API).
🌈 Some use cases of React useEffect hook:
⚡ 3. useContext( ) Hook:
👉 To understand the useContext( ) hook properly, first we have to understand what "Context" stands for...🤔
✨ Context provides a way to pass data through the component tree without having to pass props down manually at every level. ✨
👉 In a typical React application, we have components from Parent to children and grandchildren. Let's say we have to pass some data from parent component to grandchild component, to do that we need to pass the data from each and every component to the last component. This is known as prop drilling.
In this one the data is passed top-down (parent to child) via props. But that method can be clumsy for certain data.
👉 So to overcome that Context comes into the picture. The context provides a way to share values between components without having to explicitly pass a prop through every level of component tree.
🤷♂️ When should we use Context ? 🤔
👉 If the data is supposed to use as "Globally" then we should use context. Basically, context is designed to share data that can be considered "global" for a tree of react components.
🌈 So in order to apply the methods of context, we have React Context API.
👉 It is used to create a context object. When React renders a component that subscribes to this context object it will read the value of this context.
👉 Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.
👉 Basically once we wrap our parent component with the context provider the parent component and as well as child component can access to the prop value given by the Context Provider using useContext( ) hook.
👉 The useContext( ) hook is used to store the context for a React component through a context provider.
👉 Wrap the provider to the component like below
👉 The value of the context will be the value passed to the nearest parent provider.
👉 When the nearest parent provider updates, will get re-rendered with the latest context value.
👉 There are other Hooks as well in React. Will try to continue it as series. Stay Tuned.