DEV Community

loading...
Cover image for Understand React Js Hooks once and for all | part I

Understand React Js Hooks once and for all | part I

Dimer Bwimba
Coding mean๐Ÿ‘:) ๐Ÿฅ‡ . Die having memories don't die with just dreams. Take care of your body, it's the only place you have to lv
ใƒปUpdated on ใƒป6 min read

You'll already know now The React framework includes react hooks. Witch are Special hook functions that can be called from within a component.

  function component(){

      //your react hook 

  return <>UI</>
}
Enter fullscreen mode Exit fullscreen mode

So By defining functions, we may create static or dumb react components. And UI components, on the other hand, are frequently dynamic; they may need to change the state of their data, respond to lifecycle events, and access items from the DOM, among other things.

1) Reactive State >

function Component(){

   const [state] = useState('๐Ÿ')

  return <>UI</>
}
Enter fullscreen mode Exit fullscreen mode

2) Side Effects > ๐Ÿ”› > Effects > ๐Ÿ“ด

function Component(){

  useEffect(() => alert('๐Ÿ’ƒ'))

  return <>UI</>
}
Enter fullscreen mode Exit fullscreen mode

3) Grab > HTML5 > Elements > โญ

function Component(){

  const el = useRef('๐Ÿ˜Š')

  return <>UI</>
}
Enter fullscreen mode Exit fullscreen mode

...more

๐Ÿ˜ ๐Ÿ˜ ๐Ÿ˜ ๐Ÿ˜ ๐Ÿ˜ 
But prior to react version 16.8, developers were required to write classes to take advantage of certain react features.

๐Ÿ˜ ๐Ÿ˜ ๐Ÿ˜ ๐Ÿ˜ ๐Ÿ˜ 

Before

class btn extends React.Component{
     constructor(props) {
       super(props);
       this.state = {
         count:0
       }
     }
     render() {
       return (
         <p>{this.state.count}</p>
     );
  }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ˜Š๐Ÿ˜Š๐Ÿ˜Š๐Ÿ˜Š

After

function Btn(){

   const [state] = useState({count:0})

   return <p>{state.count}</p>

}
Enter fullscreen mode Exit fullscreen mode

Now you can still use classes in react ๐Ÿ˜ ...
But hooks ๐Ÿ˜Š generally provide a more ergonomic way to build components because you can reuse stateful logic without changing your component hierarchy.

๐Ÿ’ช๐Ÿ’ช๐Ÿ’ชReact has 10 built in hooks, and you'll understand what every single one of them does by the end of four part series 'articles'. In addition, you'll learn how to build your own hooks from scratch to extract your own component logic into reusable functions ๐Ÿ’ช๐Ÿ’ช๐Ÿ’ช. So follow me bruh , let learn together .

Alt Text

                #let gooooo #๐Ÿ‘ด๐Ÿ‘ด๐Ÿ‘ด๐Ÿ‘ด
Enter fullscreen mode Exit fullscreen mode

Before we dive into the react hooks world ๐Ÿ‘ด๐Ÿ‘ด, it's helpful to understand why hooks exist in the first place. In the past stateful logic or data that changes within the application was tightly coupled to a class based component. That means in order to work with reactive data, you needed to create a component that seems reasonable. But what it led to in reality was a complex tree of nested components.

๐Ÿ‘ด๐Ÿ‘ดAnd this is where I have to admit that I used to really dislike and I never learned react because sharing any logic required some frustrating โ€๐Ÿ‘ค jujitsu like higher order components and render props, which are patterns that have you passing components as arguments to other components. And that just always felt way more complex to me than patterns you find in other frameworks like Angular.

Alt Text

๐Ÿ˜Š Fortunately, ๐Ÿ˜Š hooks changed everything by giving you access to lower level features of react outside of the context of a component. When you work with hooks, you can think of them like low level primitives of the React framework that gives you special abilities that you wouldn't otherwise have in vanilla JavaScript. The hooks themselves are functions, which always start with the name of use, because you're using the super powers of the React framework. Now before you start using hooks, there's really just one rule you should be aware of.

And that's to only call them at the top level of a functional component.

Alt Text
They don't work inside of regular JavaScript functions, nested functions, loops, or anything like that.

The only exception to this rule is when building your own custom hooks, which we'll look at towards the end of these 'articles'.
Alt Text

Now the question becomes, what are these primitives or hooks actually do?

Let's break them down one by one, starting with useState.
Alt Text

useState is easily the most important and often used hook . The purpose of useState is to handle reactive data. any data that changes in the application is called state. And when the state changes, you want react to update the UI. So the latest changes are reflected to the end user.

The hook takes one optional argument, which is the default state, which we'll go ahead and set to zero the function and returns an array that contains two values you can use within your component.

Alt Text

The reason they're returned in an array is because we can destructur them with JavaScript to easily assign the values to local variables that we can name whatever we want.

The first value is the reactive data or state. If we then reference it in the UI, and its value changes in the future, React will automatically rebuild the UI to show the latest value, it'll start with a value of zero our default in the hook.

But how do we then change its value in the future, the second element in the array is a setter function. For example, we might listen to the on click event on the button, and when clicked will call the set count function to increment the count by one.

Alt Text

๐Ÿ˜ If we compare this code to a class based component, you can see
down bellow it's far more complex.

Alt Text

๐Ÿ˜ We need a class to extend a react component than a constructor to initialize the state. And also notice how we're required to reference the this keyword all over the place.useState in my opinion is a much cleaner solution.

Now we're ready to tackle the second most important hook useEffect.

Alt Text

Also happens to be one of the most #confusing to me and many other . So in order to understand it, you first need to understand the component lifecycle.

Down below is a simplified breakdown of the component lifecycle, the component is added to the UI or mounted, which can only happen once then reactive data on the component can change or it's updated, which can happen multiple times. Then finally, at some point, that component will be removed from the UI or unmounted.

Alt Text

Now keep these three lifecycle events or side effects in mind as we talk about the use effect hook, which allows us to implement logic for all of them from within a single function API.

UseEffect is a function that takes a function you define as its first argument, React will then run your function or a side effect after it is updated the DOM with the current implementation, it will run this function anytime stateful data changes on the component. That means it'll run once when the component is initialized with a default value, then run again each time the state or account is updated.

Alt Text

๐Ÿ’ช๐Ÿ’ช๐Ÿ’ชIn most cases, though, you'll likely want more fine grained control over that behavior. For example, imagine we need to fetch data when the component is first initialized, then update the state asynchronously after the data has been fetched.

Alt Text

This previews code in the image would result in an infinite loop. Because every time we do the fetch, we then update the state, which then triggers another fetch, and so on forever.

The way we address this is by adding a second argument to use a fact, which is an array of dependencies. If you add an empty array, it means there are no dependencies, which means it will only run once when the component is first initialized. But in other cases, you might want to rerun the function anytime certain staple data has changed, you can do that by adding the state to the dependencies array.

Alt Text

Now react will track that value, and any time it changes, it will rerun this function.

Now one last thing you might want to do with useEffect is run some teardown code when the component is destroyed. The way we implement a teardown function is to return a function from our use effect callback, React will take the function returned here, then call it when the component is destroyed.

Alt Text

And with that, let's move on to our next hook useContext.

This hook allows you to work with react context API, which itself is a mechanism that allows you to share or scope values throughout the entire component tree.

Part 2. Tomorrow => My Website

Alt Text

Discussion (14)

Collapse
chansenwebdev profile image
Chris Hansen

Looking forward to useContext because redux makes me ๐Ÿ˜ก๐Ÿ˜ก๐Ÿ˜ก๐Ÿ˜ก๐Ÿ˜…

Collapse
ericchapman profile image
Eric The Coder

For Redux, I did a post (last week) on dev.to that explain the Redux for beginner: dev.to/ericchapman/redux-beginner-...

Collapse
ivanjeremic profile image
Ivan Jeremic

Avoid learning Flux๐Ÿ˜ก๐Ÿ˜ก๐Ÿ˜ก

Collapse
dimer191996 profile image
Dimer Bwimba Author

yo , your post is on point , very very helpful , thank you.

Collapse
kongebra profile image
Svein Are Danielsen

Take a look at Redux Toolkit ๐Ÿ˜

Collapse
dimer191996 profile image
Dimer Bwimba Author • Edited

like fr bruh , ๐Ÿ˜ก๐Ÿ˜ก๐Ÿ˜…๐Ÿ˜…๐Ÿ˜…๐Ÿ˜… ,

Collapse
dimer191996 profile image
Dimer Bwimba Author

happy coding

Collapse
ericchapman profile image
Eric The Coder

High quality post. Thanks!

Collapse
dimer191996 profile image
Dimer Bwimba Author

thank you

Collapse
aindriu profile image
Aindriรบ Mac Giolla Eoin

destructur should be destructor

Collapse
dimer191996 profile image
Dimer Bwimba Author

for sure

Some comments have been hidden by the post's author - find out more