DEV Community

Cover image for React Hooks with examples( useState, useEffect, useContext ).
Utkarsh Yadav
Utkarsh Yadav

Posted on β€’ Edited on

3 1

React Hooks with examples( useState, useEffect, useContext ).

Hey! Programmers. Have you ever thought about how React helps us in making a complicated site or an application ?. To develop a large scale application we need to handle a bunch of states and data throughout our application and this in result requires a complicated and well maintained but yet a fragile codebase. This Fragility of the codebase is kind of obvious due to many states and use cases remained UN-handled. To solve this problem React was made available and provided us with many advantages.

One of the main advantages of React framework after the component lifecycle methods is REACT HOOKS, think of it, as an abstract to reduce the code written while using class-based components and lifecycle methods.

  • Reduces Code.
  • Improves scalability.
  • Provide a clear meaning to the data flow.

This post consists only useState, useEffect, useContext Hooks. So without wasting anyone time let's just jump right into understanding each of them together.

useState Hook

syntax:

const [state, setState] = useState(initialState);
Enter fullscreen mode Exit fullscreen mode

terminology:

  • state: the data that is inside the state and ready to be used.
  • setState:: this helps in changing the state that is initially set to some value and ready to be manipulated via some functions or an event.
  • initialState: The initial state that is set by default as a component renders which got change afterwards.

The complexity that can be increased to use useState

const [state, setState] = useState({
  array[], // array of string, object, number etc.
  object,  // object
  string,
  number
});
Enter fullscreen mode Exit fullscreen mode

Examplar CODE :

import React, { useState } from "react";

function App() {
  const [like, setLike] = useState(0);

  return (
    <div>
      <h3>πŸ’œ : {like}</h3>
      <button onClick={() => setLike((liked) => liked + 1)}>
        Like πŸ‘
      </button>
      <button onClick={() => setLike((liked) => liked - 1)}>
        unLike πŸ‘Ž
      </button>
      <button onClick={() => setLike(0)}>Reset</button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The first statement is for importing the hook from react library.
  • The 3 Rules to remember while using useState.
const [like, setLike] = useState(0);
//Rule 1: This statement means that initially like value is: 0
//Rule 2: After any event, we need to manipulate like using setLike.
//Rule 3: And log `like` to see the state change.
Enter fullscreen mode Exit fullscreen mode
  • The Code to increment likes. In this code, when onClick Event is trigerred we call setLike and increment the value by passing an iterator liked and incrementing liked state whenever user clicks to like button.
<h3>πŸ’œ : {like}</h3>
<button onClick={() => setLike((liked) => liked + 1)}>
  Like πŸ‘
</button>
Enter fullscreen mode Exit fullscreen mode
  • The Code to decrement likes. In this code, when onClick Event is trigerred we call setLike and decrement the value by passing an iterator liked and decrementing liked state whenever user clicks to like button.
 </button>
 <button onClick={() => setLike((liked) => liked - 1)}>
  unLike πŸ‘Ž
</button>
Enter fullscreen mode Exit fullscreen mode
  • To RESET the state, i have just reset the state to 0 by calling setLike and explicitly returning 0.
<button onClick={() => setLike(0)}>Reset</button>
Enter fullscreen mode Exit fullscreen mode

Screencasts:

Alt Text

This blogPost is short to help you digest what you have learned. Need to wait for useEffect and useContext. will link it soon.

Thanks for Reading.
Happy Coding.

Please Do Comment!

Dont's Stop Learning Next BlogPost.

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
abdulazizalmalki profile image
Abdulaziz Almalki β€’

You promised but you didn't deliver.

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay