DEV Community

Cover image for πŸ”₯ React Hooks.😎
Shaik Dawood
Shaik Dawood

Posted on • Updated 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.

Discussion (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 Author

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

Nice!