DEV Community

Cover image for ๐Ÿ”ฅ React Hooks.๐Ÿ˜Ž
Shaik Dawood
Shaik Dawood

Posted on • Edited on

๐Ÿ”ฅ React Hooks.๐Ÿ˜Ž

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

๐Ÿ‘‰ 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( ):

examples of 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:
useEffect Syntax

Syntax:

  1. The first argument in useEffect is to give side effects function.
  2. 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:

  1. 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.

  2. 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.

  3. 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.

  4. 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:

  • Always run whenever component renders/re-renders.
    usecase1

  • Run once after that if component re-renders, then it will not run.
    usecase2

  • Run once by default after that if prop values changes, then run.
    usecase3

  • Run once by default after that if state changes than run.
    usecase4

โšก 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.

Props

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:

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:

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

context

  • ๐Ÿ‘‰ Access the context like below inside myComponent
    access Context

  • ๐Ÿ‘‰ 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.

If you liked this post, please react and let me know what you think in the comments! See you in next Article. Goodbye.

Top comments (3)

Collapse
 
leandroreschke profile image
Leandro Reschke

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!

Collapse
 
dawoodxp97 profile image
Shaik Dawood

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.

Collapse
 
wkylin profile image
wkylin.w

Nice!