React Hooks Tutorial with Examples

This article was originally published at https://www.blog.duomly.com/react-hooks-tutorial-with-examples/


Usually, most of the front-end frameworks updates don’t bring huge changes, but it was different in February 2019, when Facebook released 16.8 version of React with hooks.

They introduced Hooks API, a functionality which, in my opinion, makes things easier because it allows using of functional components a similar way as we used class components until that time.

As in the beginning, Hooks API was just used by some curious developers to check what’s inside, today it’s officially recommended to use it.

I one of the last projects I’ve been working on, I had a chance to try hooks, and use them across all the application, without almost using class components, and I easily can say that hooks are awesome!

Today, I’d like to explain to you the hooks which we can use in our React.js applications and also show some code examples where hooks can be used instead of the class component!

And of course, like always, if you prefer watching instead of reading, join me at Duomly’s Youtube channel, where I publish videos about almost everything I write here.

Let’s get into hooks!

1. What are React Hooks?

In the beginning, I’d like to answer the most critical question you may ask yourself right now „What are React Hooks?”.

Hooks API is a set of built-in functions that allow developers to use the state and lifecycle methods in the functional components. So, with hooks, functional components can handle UI, state, and logic of the component as well.

The good news is that hooks work with the existing code, so you don’t have to rebuild all your application to try hooks, you can do it in the new feature if you wish to try it.

Let’s see why it’s a good idea to use hooks.

2. Why using hooks is a good idea?

There are some common benefits of using React Hooks API, which is often highlighted by frontend programmers. Let me present to you some of them.
  • First of all, React Hooks allow us to create highly reusable, isolated components and help us to avoid unnecessary logic.
  • It’s straightforward to work with and test.
  • It provides an improved way to share logic across different components.
  • The code written with hooks is very often less complicated and looks cleaner.
  • In Javascript, a minified function is less code than a minified class.
So, if we already know what and why let’s check what are the rules of hooks set by the React creators.

3. Rules of hooks

In official React documentation we can find two rules telling us about using hooks:
„Only call hooks at the top level”
This means that hooks can’t be called inside the loops, nested functions, conditions. They should be used only at the top level of the functions.
„Only call hooks from React functions”
Hooks should be called only in React functions, it’s a bad practice to all them from plain Javascript functions. In practice, it means that hooks should be called only in React functional components or inside the custom hooks.

There’s also a piece of good news! React developers prepared a linter plugin to make sure those rules are respected. If you’d like to use it, here’s the link - https://www.npmjs.com/package/eslint-plugin-react-hooks

4. Basic hooks

Now, let’s take a closer look at the actual hooks. There are three basic hooks in React.js documentation, but as I’d like to explain to you the hooks which are the most useful, we are going to take a look at just two of them: useState() and useEffect().

useState()

I’d like to start from useState() which is the most basic React hook. It allows using state inside the functional component. Let’s see, what’s the syntax of useState().
const [number, setNumber] = useState(initNumber);
In the code example below you can see an array, the number is stateful value, setNumber is a function to update it, and initNumber is the initial value. Easy, right?

Now let me show you an example of a form component where we can add personal income or outcome to the list.

* Code in the example is build using Bulma CSS framework.

import React, {useState} from 'react';

const AccountBalance = () => {
  const [balance, setBalance] = useState(1500);
  const [savingBalance, setSavingBalance] = useState(1349);

  const handleSavings = () => {
    setBalance(balance - 100);
    setSavingBalance(savingBalance + 100);
  }

  const handleSpending = () => {
    setBalance(balance + 100);
    setSavingBalance(savingBalance - 100);
  }

  return (
    <div className="columns">
      <div className="column">
        <div className="box">
          <h4 className="title is-4">Your account balance:</h4>
          <div className="amount">{balance}$</div>
          <button
            className="button is-info"
            onClick={() => handleSavings()}
          >
            Send 100$
          </button>
        </div>
      </div>
      <div className="column">
        <div className="box">
          <h4 className="title is-4">Your savings balance:</h4>
          <div className="amount savings">{savingBalance}$</div>
          <button
            className="button is-info"
            onClick={() => handleSpending()}
          >
            Send 100$
          </button>
        </div>
      </div>
    </div>
  )
}

export default AccountBalance;

I also added some CSS to get a pretty result. So, I’ll attach all the CSS code at the end of this article.

And here is the result of the code.

Duomly - Programming Online Courses - React.js Hooks Tutorial

In the code above you can see how useState() allows us to handle stateful values.

useEffect()

The other basic hook in React is useEffect(). It’s kinda like componentDidMount or other componentDidUpdate in the class component.

By default, it’s running every re-render but it’s possible to set it to run only once or only if the specified value has changed.

Let’s see the syntax of useEffect() hook.

useEffect(() => {
    // do something
}, [value])

Value passed at the end of useEffect in the array are the ones which will decide about calling the code at each re-render.

It also may contain a cleanup function, for example, if you are starting a subscription or timer, then it may be useful. Let’s see, how it works on a code example. I’m going to use the previous component and add there a check for value account and notification.

import React, {useState, useEffect} from 'react';

const AccountBalance = () => {
  const [balance, setBalance] = useState(1500);
  const [savingBalance, setSavingBalance] = useState(1349);
  const [notification, setNotification] = useState(false);

  const handleSavings = () => {
    if (balance > 1000) {
      setBalance(balance - 100);
      setSavingBalance(savingBalance + 100);
    }
  }

  const handleSpending = () => {
    setBalance(balance + 100);
    setSavingBalance(savingBalance - 100);
  }

  useEffect(() => {
    if (balance <= 1000) {
      setNotification(true);
    }
  }, [balance]);

  return (
    <div className="columns">
      <div className="column">
        <div className="box">
          <h4 className="title is-4">Your account balance:</h4>
          <div className="amount">{balance}$</div>
          <button
            className="button is-info"
            onClick={() => handleSavings()}
          >
            Send 100$
          </button>
        </div>
      </div>
      <div className="column">
        <div className="box">
          <h4 className="title is-4">Your savings balance:</h4>
          <div className="amount savings">{savingBalance}$</div>
          <button
            className="button is-info"
            onClick={() => handleSpending()}
          >
            Send 100$
          </button>
        </div>
      </div>
      {notification && (
        <div className="notification is-danger">
          <button onClick={() => setNotification(false)} className="delete"></button>
          <p>Your account balance is very low.</p>
          <p>You can't transfer more money today.</p>
        </div>
      )}
    </div>
  )
}

export default AccountBalance;

And here is the visual representation of the code above.

Duomly - Programming Online Courses - React.js Hooks Tutorial

5. Redux hooks

I’d like to write a little bit about handling redux store with hooks because it’s also possible.

There are also two important hooks for redux, and they are described pretty well in redux documentation. It’s useSelector() and useDispatch().

useSelector()

The useSelector() hook is used to access data from the redux store. It works like mapStateToProps and should be used instead.

This hook is called every time when functional component renders and whenever action is dispatched.

Let’s take a quick look at the simple example of redux useSelector() hook on our component:

import React from 'react'
import { useSelector } from 'react-redux'

const AccountBalance = () => {
const balance = useSelector(state => state.user.accountBlance);
const savingBalance = useSelector(state => state.user.savingBlance);

return (
<div className=“columns”>
<div className=“column”>
<div className=“box”>
<h4 className=“title is-4”>Your account balance:</h4>
<div className=“amount”>{balance}$</div>
</div>
</div>
<div className=“column”>
<div className=“box”>
<h4 className=“title is-4”>Your savings balance:</h4>
<div className=“amount savings”>{savingBalance}$</div>
</div>
</div>
</div>
);
}

export default AccountBalance;

useDispatch()

When you create an action and you want to call it in the component, useDispatch() hook is a great solution. It’s a reference to the dispatch function from the Redux store. Let’s take a look at the syntax of the useDispatch() code example:
const dispatch = useDispatch();
dispatch(action(params));
So, first, we create dispatch constant, and then we can use it to dispatch an action from redux. Let’s see how it would work in our example component.

And as I promised here is the CSS code which I added to my app to get the results as on the image:

body {
  background-color: rgb(4, 0, 48);
  height: 100vh;
  position: relative;
}

.container {
height: 100vh;
}

.box {
background-color: #282e5c;
color: white;
text-align: center;
}

.title {
color: white;
}

.amount {
position: relative;
}

.amount {
border: 10px solid hsl(171, 100%, 41%);
display: inline-flex;
align-items: center;
justify-content: center;
color: white;
min-width: 1em;
border-radius: 50%;
vertical-align: middle;
padding: 4%;
font-size: 26px;
font-weight: bold;
}

.amount:before {
content:‘’;
float: left;
width: auto;
padding-bottom: 100%;
}

.savings {
border-color: hsl(48, 100%, 67%);
}

.button {
display: block;
width: 30%;
margin: auto;
margin-top: 10%;
color: white;
}

.notification {
position: absolute;
bottom: 20px;
right: 0px;
font-weight: bold;
}

Conclusion

In this article, I explained to you what are hook, and we went through the most popular ones with examples.

I’ve created a functional component (I hope you did as well), where I’m sending money from one to the other account. For UI I used Bulma framework because it’s fast, easy, and simple.

I hope, based on the article I’ve created you can jump into another React.js project and try using hooks by yourself, as it’s a really cool solution.

If you’d like to learn more about React.js, then check out two more articles I’ve created some time ago, What is React.js and why it’s worth to learn? and How to create React app in 5 minutes?.

The second one will definitely help you to set up the React.js project if you can’t do it yet.

Let me know in the comments if you like working with hooks and if you find it useful.

Thank you for reading,
Anna from Duomly

#javascript #reactjs #redux #es6 #web-development

What is GEEK

Buddha Community

React Hooks Tutorial with Examples
Lawrence  Lesch

Lawrence Lesch

1677668905

TS-mockito: Mocking Library for TypeScript

TS-mockito

Mocking library for TypeScript inspired by http://mockito.org/

1.x to 2.x migration guide

1.x to 2.x migration guide

Main features

  • Strongly typed
  • IDE autocomplete
  • Mock creation (mock) (also abstract classes) #example
  • Spying on real objects (spy) #example
  • Changing mock behavior (when) via:
  • Checking if methods were called with given arguments (verify)
    • anything, notNull, anyString, anyOfClass etc. - for more flexible comparision
    • once, twice, times, atLeast etc. - allows call count verification #example
    • calledBefore, calledAfter - allows call order verification #example
  • Resetting mock (reset, resetCalls) #example, #example
  • Capturing arguments passed to method (capture) #example
  • Recording multiple behaviors #example
  • Readable error messages (ex. 'Expected "convertNumberToString(strictEqual(3))" to be called 2 time(s). But has been called 1 time(s).')

Installation

npm install ts-mockito --save-dev

Usage

Basics

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance from mock
let foo:Foo = instance(mockedFoo);

// Using instance in source code
foo.getBar(3);
foo.getBar(5);

// Explicit, readable verification
verify(mockedFoo.getBar(3)).called();
verify(mockedFoo.getBar(anything())).called();

Stubbing method calls

// Creating mock
let mockedFoo:Foo = mock(Foo);

// stub method before execution
when(mockedFoo.getBar(3)).thenReturn('three');

// Getting instance
let foo:Foo = instance(mockedFoo);

// prints three
console.log(foo.getBar(3));

// prints null, because "getBar(999)" was not stubbed
console.log(foo.getBar(999));

Stubbing getter value

// Creating mock
let mockedFoo:Foo = mock(Foo);

// stub getter before execution
when(mockedFoo.sampleGetter).thenReturn('three');

// Getting instance
let foo:Foo = instance(mockedFoo);

// prints three
console.log(foo.sampleGetter);

Stubbing property values that have no getters

Syntax is the same as with getter values.

Please note, that stubbing properties that don't have getters only works if Proxy object is available (ES6).

Call count verification

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
foo.getBar(1);
foo.getBar(2);
foo.getBar(2);
foo.getBar(3);

// Call count verification
verify(mockedFoo.getBar(1)).once();               // was called with arg === 1 only once
verify(mockedFoo.getBar(2)).twice();              // was called with arg === 2 exactly two times
verify(mockedFoo.getBar(between(2, 3))).thrice(); // was called with arg between 2-3 exactly three times
verify(mockedFoo.getBar(anyNumber()).times(4);    // was called with any number arg exactly four times
verify(mockedFoo.getBar(2)).atLeast(2);           // was called with arg === 2 min two times
verify(mockedFoo.getBar(anything())).atMost(4);   // was called with any argument max four times
verify(mockedFoo.getBar(4)).never();              // was never called with arg === 4

Call order verification

// Creating mock
let mockedFoo:Foo = mock(Foo);
let mockedBar:Bar = mock(Bar);

// Getting instance
let foo:Foo = instance(mockedFoo);
let bar:Bar = instance(mockedBar);

// Some calls
foo.getBar(1);
bar.getFoo(2);

// Call order verification
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(2));    // foo.getBar(1) has been called before bar.getFoo(2)
verify(mockedBar.getFoo(2)).calledAfter(mockedFoo.getBar(1));    // bar.getFoo(2) has been called before foo.getBar(1)
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(999999));    // throws error (mockedBar.getFoo(999999) has never been called)

Throwing errors

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(10)).thenThrow(new Error('fatal error'));

let foo:Foo = instance(mockedFoo);
try {
    foo.getBar(10);
} catch (error:Error) {
    console.log(error.message); // 'fatal error'
}

Custom function

You can also stub method with your own implementation

let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);

when(mockedFoo.sumTwoNumbers(anyNumber(), anyNumber())).thenCall((arg1:number, arg2:number) => {
    return arg1 * arg2; 
});

// prints '50' because we've changed sum method implementation to multiply!
console.log(foo.sumTwoNumbers(5, 10));

Resolving / rejecting promises

You can also stub method to resolve / reject promise

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.fetchData("a")).thenResolve({id: "a", value: "Hello world"});
when(mockedFoo.fetchData("b")).thenReject(new Error("b does not exist"));

Resetting mock calls

You can reset just mock call counter

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
foo.getBar(1);
foo.getBar(1);
verify(mockedFoo.getBar(1)).twice();      // getBar with arg "1" has been called twice

// Reset mock
resetCalls(mockedFoo);

// Call count verification
verify(mockedFoo.getBar(1)).never();      // has never been called after reset

You can also reset calls of multiple mocks at once resetCalls(firstMock, secondMock, thirdMock)

Resetting mock

Or reset mock call counter with all stubs

// Creating mock
let mockedFoo:Foo = mock(Foo);
when(mockedFoo.getBar(1)).thenReturn("one").

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
console.log(foo.getBar(1));               // "one" - as defined in stub
console.log(foo.getBar(1));               // "one" - as defined in stub
verify(mockedFoo.getBar(1)).twice();      // getBar with arg "1" has been called twice

// Reset mock
reset(mockedFoo);

// Call count verification
verify(mockedFoo.getBar(1)).never();      // has never been called after reset
console.log(foo.getBar(1));               // null - previously added stub has been removed

You can also reset multiple mocks at once reset(firstMock, secondMock, thirdMock)

Capturing method arguments

let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);

// Call method
foo.sumTwoNumbers(1, 2);

// Check first arg captor values
const [firstArg, secondArg] = capture(mockedFoo.sumTwoNumbers).last();
console.log(firstArg);    // prints 1
console.log(secondArg);    // prints 2

You can also get other calls using first(), second(), byCallIndex(3) and more...

Recording multiple behaviors

You can set multiple returning values for same matching values

const mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(anyNumber())).thenReturn('one').thenReturn('two').thenReturn('three');

const foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(1));    // two
console.log(foo.getBar(1));    // three
console.log(foo.getBar(1));    // three - last defined behavior will be repeated infinitely

Another example with specific values

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(1)).thenReturn('one').thenReturn('another one');
when(mockedFoo.getBar(2)).thenReturn('two');

let foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(2));    // two
console.log(foo.getBar(1));    // another one
console.log(foo.getBar(1));    // another one - this is last defined behavior for arg '1' so it will be repeated
console.log(foo.getBar(2));    // two
console.log(foo.getBar(2));    // two - this is last defined behavior for arg '2' so it will be repeated

Short notation:

const mockedFoo:Foo = mock(Foo);

// You can specify return values as multiple thenReturn args
when(mockedFoo.getBar(anyNumber())).thenReturn('one', 'two', 'three');

const foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(1));    // two
console.log(foo.getBar(1));    // three
console.log(foo.getBar(1));    // three - last defined behavior will be repeated infinity

Possible errors:

const mockedFoo:Foo = mock(Foo);

// When multiple matchers, matches same result:
when(mockedFoo.getBar(anyNumber())).thenReturn('one');
when(mockedFoo.getBar(3)).thenReturn('one');

const foo:Foo = instance(mockedFoo);
foo.getBar(3); // MultipleMatchersMatchSameStubError will be thrown, two matchers match same method call

Mocking interfaces

You can mock interfaces too, just instead of passing type to mock function, set mock function generic type Mocking interfaces requires Proxy implementation

let mockedFoo:Foo = mock<FooInterface>(); // instead of mock(FooInterface)
const foo: SampleGeneric<FooInterface> = instance(mockedFoo);

Mocking types

You can mock abstract classes

const mockedFoo: SampleAbstractClass = mock(SampleAbstractClass);
const foo: SampleAbstractClass = instance(mockedFoo);

You can also mock generic classes, but note that generic type is just needed by mock type definition

const mockedFoo: SampleGeneric<SampleInterface> = mock(SampleGeneric);
const foo: SampleGeneric<SampleInterface> = instance(mockedFoo);

Spying on real objects

You can partially mock an existing instance:

const foo: Foo = new Foo();
const spiedFoo = spy(foo);

when(spiedFoo.getBar(3)).thenReturn('one');

console.log(foo.getBar(3)); // 'one'
console.log(foo.getBaz()); // call to a real method

You can spy on plain objects too:

const foo = { bar: () => 42 };
const spiedFoo = spy(foo);

foo.bar();

console.log(capture(spiedFoo.bar).last()); // [42] 

Thanks


Download Details:

Author: NagRock
Source Code: https://github.com/NagRock/ts-mockito 
License: MIT license

#typescript #testing #mock 

Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

Hayden Slater

1599277908

Validating React Forms With React-Hook-Form

Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long. This is can be easily done using React Hook From. In this article, I will show you how.

Required Fields

The most simple, yet very common, validation is to make sure that an input component contains input from the user. React Hook Form basic concept is to register input tags to the form by passing register() to the tag’s ref attribute. As we can see here:

#react-native #react #react-hook-form #react-hook