React Hooks

React Hooks

React Hooks is a relatively new phenomenon that has braced the react community, it aims to solve complaints, that the React-Redux flow cannot only be a lot complicated but just a lot in general.

It is chiefly used to create and manage state in small projects so that we do not need to introduce Redux, which is significantly a lot more complicated. React-hooks is built on the idea that functional components should be allowed to make use of states without having to make them a Class component.

React Hooks comes out of the box in projects with React versions of 16.8 and above.

The State Hook

The useState Hook gives our functional components the ability to use states in them.

example


Import React, { useState } from react;

const App = () => {

const [ name, setName ] = useState( ‘Amara’);

return (

<div>
      <p> { name } </p>
      <button onClick={() => setName( ‘ Sharon ‘ ) > Change Name </button>
</div>

)
};

explanation

One relatively new to react hooks might see this piece of code and think, ‘this is even more complicated'. In reality, it is not, as this contains a lot ( if not all ) of the parts and ways we thought about original React.

In the example above, we use array destructuring that is available to us as a result of the useState Hook. The first expression in the array is a variable, and the second expression is a function that would be used to change the value of the variable. The useState Hook takes in one parameter, which is the original or the default value of the variable.

In the block of code above the variable is name, and the function used to change the name variable is setName. The rules are not written, but it is always a good practice when naming the function to use a 'set' prefix, then the variable( in this case name ). Then the string ‘Amara ‘is passed as the one parameter in the useState.

In an attempt to make React Hooks easier to understand, I will show you the equivalent piece of code in native React.

React Hooks

const [ name, setName ] = useState( ‘Amara’);

Native React

this.state = {
name : 'Amara ‘
}

The button that would be used to change the state would be written as thus:

React Hooks

<button onClick={() => setName( ‘ Sharon ‘ ) > Change Name </button>

Native React

<button onClick={ this.setState( {name :Sharon ’}) > Change Name </button>

The Effect Hook

The useEffect Hook bears a semblance to the native React componentDidMount lifecycle method, as it takes in 2 parameters, the first one which is the block of code we want to run and the second is what parameters ( when changed or updated ) determines when to run the block of code in the first parameter.

Passing no value in the second parameter runs the code every time the component re-renders, passing an empty array as the second parameter runs the code only once.

example

import React, { useState, useEffect } from react;

const [ name, setName ] = useState( ‘Amara’);

useEffect(() => {
console.log(name)
}, [name])

explanation

In this example, the name variable state is responsible for running the function that console.logs the name variable. Thus anytime the name variable changes, the function console.logs the new value of the name variable.

wait what about componentWillUnMount?

We have discussed how useEffect Hook can be likened to the ComponentDidMount lifecycle method, what about the ComponentWillUnMount lifecycle method, how can we detect when a component unmounts and run a function then.

useEffect(() => {
console.log( ‘ I am mounted ‘ );

return () => {
console.log( ‘ I am unmounted ‘ )
}
});

explanation

When the component the use effect is written in mounts first, it logs ‘ I am mounted ‘ to the console.

The return returns a function that console.logs ‘ I am unmounted ‘ when the component unmounts( that is, gets removed from our tree ).

useReducer

The useReducer as its name suggests uses reducers and a lot of the parts of the Redux syntax in managing states.

import React, { useReducer, useEffect } from react;

const INITIAL_STATE = {
name: ‘ Amara ‘
}

const reducer = ( state, action )  => {
     switch( action.type ){
         case ‘ SET_NAME' :
           return { name : action.payload }
      default:
       return state ;
     }
};

const setName =  name => {
    type: ‘SET_NAME',
    payload: name
}




const newReducerExample = () => {
const [ state, dispatch ] = useReducer( reducer, INITIAL_STATE);

useEffect(() => {
      dispatch( setName ( ‘Sharon ‘)
}, [ name ])

return (
  <p>{this.state.name}</p>
)
}

The reducer which we created, whose name coincidentally, is also reducer, takes in 2 parameters, a state ( the initial state), and an action( setName ).

We use a switch statement to check if the action.type of the action and the action type of the case that’s trying to change the state or disperse the action are the same. Then we disperse it. This causes the state to change and the whole component to render.

The useReducer Hook takes in two parameters, the reducer, ( which in this case is reducer ) and the initial state ( INITIAL_STATE ). With array destructuring, we get the state and the dispatch method which we use to dispatch our action.

This seems long to change just a name property, but it is usually used to fetch data, change names, and in more complicated state management applications.

Conclusion

In this article, we discussed the different Hooks and how they could be utilized in our code. In this article we frequently referenced the native React and Redux syntaxes, this is just an attempt to make React Hooks more digestible and relate it to concepts that you might have seen already, but if you have never used the native react and redux, you can ignore the references.

Thank you, and happy coding!