Hello everyone,๐
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.
๐ฅ 3 Rules of using Hooks:
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 syntax of Effect hook is below:
Syntax:
- 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:
Run once after that if component re-renders, then it will not run.
Run once by default after that if prop values changes, then run.
โก 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.
- React.createContext:
๐ 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.
- Context.Provider:
๐ 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.
Summarization of useContext: ๐ฅ
๐ 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.
And Much Moreโฆ๐ฅ๐
๐ There are other Hooks as well in React. Will try to continue it as series. Stay Tuned.
Top comments (3)
Awesome! You explained it so well, that only now I understand useEffect.
I have a suggestion, could you also show wrong cases? For example when you shouldn't use useState and instead use a normal variable, or when you shouldn't use useEffect and instead only a normal function, maybe it will help understand it even better.
Sometimes I struggle to decide if I need it or not, like when making a Login screen, it's going to check with an API if the user is valid before, should I use useEffect? Or a normal function tied to a form and set a loading animation.
Anyway, great article, thank you!
Thank you ๐.
Yes, nice suggestion. I'll make sure to update the Bad Practices of Hooks in a separate blog stay tuned for it.
The use of useEffect will depends on requirement, basically the useEffect is used to execute a particular code that needs to happen during lifecycle of the component instead of on specific user interactions or DOM events.
As in your case, I'd definitely suggest you to use useEffect for checking the user login with API. Make sure to use the side effect as "Empty Dependency Array" in useEffect. So it will run once the app completes initial Render.
Hope you've got an Idea about it.. Thank You.
Nice!