Showing posts with label React Hooks. Show all posts
Showing posts with label React Hooks. Show all posts

Friday, May 8, 2020

React 16.8 Hooks

useEffect Hook example in React 16.8

In the previous post we saw an example of how to use the useState hook in a function component to maintain and update state props. In this post we will see an example on how to use the useEffect hook to perform side effects from a function component.

In this sample, we will use the useEffect hook to change the title of the document. We will use the value from the state prop title to set the document title as Hello + {title}. Initially the title will be displayed as Hello React, on clicking a button we change the state value of title, which in-turn triggers the useEffect and changes the document title.

useState Hook example in React 16.8

In the previous post we saw that the useState Hook is used to define state props in a function component, in this post we shall see a small example on how the useState hook works in action.

In this post we will create a function component and define a state prop count using the useState hook, we will attach a function setCount which will be used to change the value of the count prop. We will also attach the setCount function to the click event handler of a button, so that each time the button is clicked the setCount function will be called which will increase the value of the count state prop by 1.

Hooks in React 16.8

Hooks were introduces in React 16.8, hooks let us create function components in React with state and other React features. Usually for a React component to have state it should be created as a class component.

React 16.8 introduces the following basic hooks