React Hooks Basics

Hooks were added to React in version 16.8.

Hooks allow function components to have access to state and other React features. Because of this, class components are generally no longer needed.

📌 State Hook

🎈useState() is a Hook that lets you add a piece of state to your component.

useState accepts an initial state and returns two values:

  • The current state.
  • A function that updates the state.
const [count, setCount] = useState(0);

The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination of these!

🎈useReducer Hook is similar to the useState Hook. It allows for custom state logic.

The useReducer(reducer, initialState) hook accept 2 arguments: the reducer function and the initial state. The hook then returns an array of 2 items: the current state and the dispatch function.

import { useReducer } from 'react';function MyComponent() {const [state, dispatch] = useReducer(reducer, initialState);const action = {type: 'ActionType'};return (<button onClick={() => dispatch(action)}>Click me</button>);}

📌 Effect Hook

🎈useEffect() Hook allows you to perform side effects in your components.

Some examples of side effects are: fetching data, directly updating the DOM, and timers.

useEffect accepts two arguments. The second argument is optional.

Dependencies argument of useEffect(callback, dependencies) lets you control when the side-effect runs. When dependencies are:

  • Not provided: the side-effect runs after every rendering.
  • An empty array []: the side-effect runs once after the initial rendering.
  • Has props or state values [prop1, prop2, …, state1, state2]: the side-effect runs only when any depenendecy value changes

Some side-effects need cleanup: close a socket, clear timers.

If the callback of useEffect(callback, deps) returns a function, then useEffect() considers this as an effect cleanup:

Cleanup works the following way:

  • After initial rendering, useEffect() invokes the callback having the side-effect. cleanup function is not invoked.
  • On later renderings, before invoking the next side-effect callback, useEffect() invokes the cleanup function from the previous side-effect execution (to clean up everything after the previous side-effect), then runs the current side-effect.
  • Finally, after unmounting the component, useEffect() invokes the cleanup function from the latest side-effect.

New Hooks are coming …

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cosmin Mihalache

Cosmin Mihalache

I have been working as a web developer for over 3 years, and lately I’ve been focusing on building animations and functionalities.