React Hooks Overview In 5 Minutes

Brief Introduction About React Hooks In 5 Min.

https://howchoo.com/react/introduction-to-react-hooks

Hooks are a new addition to React 16.8. They let you use state and other React features without writing a class. We have many Hooks but some of the most commonly used hooks are:

  1. useState
  2. useEffect
  3. useRef
  4. useSelector
  5. useDispatch

So, let start with each and elaborate with a simple example:

1. useState

useState lets us take a state of each component, that we can build in whichever component we want. This State can hold any type of value. As well as it is far better than we use State in-class component because in this, we can easily modify the state by using the function like:

Syntex:

const {state, setState} = useState(initial value)

Here we have the function setState that we can name as whatever we want. and to modifying the state value we can pass the value inside the parentheses.

2. useEffect

From my point of view, this Hook is the most important hook of ReactJS. Because it let us perform the effect we want and we can handle the effect easily. For eg., if we have to call API then we use useEffect.

Basically, it is the powerful replacement of the lifecycle methods of ReactJS. Where it replaces 3 lifecycles inside one hook! isn’t it amazing !!

Syntex:

useEffect(() => {}

}, [dependency])

The dependency plays the role of handling side effects of useEffect. which tells us whenever the “dependency” called and its props changes this effect will automatically trigger(same as componentDidUpdate does).

3. useRef

This hook used to get the current value of the element and store it in .current. This hook is we also use from ‘React’ library.

Syntex:

const inputE1 =useRef(initial Value)

from : reactjs.org

4. useSelector

This hook is very useful if you’re going to use state in your code(definitely you’ll). This hook replaces the code we wrote in the class component before to get the state with the help of the mapStateToProps.

Syntex:

const StateName = useSelector((state )=> state.StateName)

We import this hook from ‘react-redux’. So, what we’re doing here is, let suppose we have the name StateName in our reducer and we just getting that state with accessing state.StateName.

5. useDispatch

when we’ve got an organized way of the project. We use dispatch to call the API actions we create. which hit the API and set the data into the reducer and back pass to the component.

While using there could be two situations like if you have dispatch in your props then you can refer this.props.dispatch or props.dispatch.

And the second case is when we’ve got no props of dispatch. Then we take the dispatch from ‘react-redux’.

Syntex:

const dispatch = useDispatch()

Let it assume API function is our Action.

Thanks For Reading!

Let me know, did you understand it or not!?

Profession: React Developer