React.js Let’s Hook part 2

Posted On 07 February 2020 ( 3.7 Minute Read )

React.js Let’s Hook part 2

this is the continued part form our last blog in React.js Let’s Hook, If you didn’t read that, I suggest you do so here

so in this blog today, We are going to talk about Hooks in detail and proceed what we have started last time. Let’s get to it!

From our last blog, we have written code like the one blow and promised to explain it in the next blog ( i.e this one ).

Here is the code, in the section below we are going to dissect the code and understand what hooks are and how they are different from the class-based component

import React from 'react';
function OurFirstHook () {
const [clicked , setClicked] = React.useState(0);
const clickedHundler = (event) => {
     setClicked(clicked+1);
}
   return (
        <div>
          <Button onClick={clickedHundler}> 
           {`button clicked ${clicked} times`}
          </Button>
        </div>
         )
}
export default OurFirstHook

In the code above as you can see there is no class. and we have used some strange word ‘ useState ‘ which is accepting a value! well, let’s try to understand how this is different from class and how we are using state.

React Hooks enables you to have state in your functional component as if they were class components! This shouldn’t be a surprise since everything in javascript is a function. a function having a state is not a different thing. but comparing to what was it is pretty different.

React hooks enable state in using a new hooks API called ‘useState’. use state expects an initial value, as classes also expect the same for their state.

const [clicked , setClicked] = React.useState(0);

But hooks also have a set state function within every state you declare. for example in the code above we have setClicked declared with clicked to enable simplifying things and also its good to not that we should manipulate simple states using useState , if we have more complex states its better to use useReducers or redux.

when referencing a hook state

return (<div>
          <Button onClick={clickedHundler}> 
           {`button clicked ${clicked} times`}
          </Button>
        </div>)

we will dive into more advanced react Hook features in the coming blogs but till then happy coding from Addis software