React Hooks in SPFx

This article provides steps to use the react hooks in the SharePoint Framework (SPFx) projects, generally, Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes. here we walkthrough react state, props, event and async functions in the FunctionComponent for SPFx.  

Why React Hooks

You can find a lot of reason why we have to use hooks is like Hooks allow you to use local state and other React features without writing a class. But the basic reason is most of them not interested to bind all the events and function to access the state values, also not interested to run super() inside the constructor and etc… 

Create a new web part project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install @pnp/sp --save

Function Component and react Props

Basically FunctionComponent is replacing the React. Component class. its is much simple, yes, just function that is all. in below example, both serves the same. you can choose either logic based on your convenient.   

you can also find the way to pass the props into your FunctionComponent

import * as React from 'react';
import { ISpfxReactHooksProps } from './ISpfxReactHooksProps';

const SpfxReactHooks: React.FunctionComponent<ISpfxReactHooksProps> = props => {
  return <div>hello from logic 1 {props.description}</div>
export default SpfxReactHooks;


import * as React from 'react';
import { ISpfxReactHooksProps } from './ISpfxReactHooksProps';

function simplehooks(props: ISpfxReactHooksProps) {
  return <div>hello from logic 2 {props.description}</div>
export default simplehooks;

React State

For use react state, we have to import separately from react and the basic syntax of the state is creating const and pass state variable name first then virtual function name then equal to useState and pass the initial value as a parameter, so inside the dom or in any event you can read and set the value for the state.  

import * as React from 'react';
import { useState } from 'react';
import { ISpfxReactHooksProps } from './ISpfxReactHooksProps';
import { PrimaryButton } from 'office-ui-fabric-react';

function simplehooks(props: ISpfxReactHooksProps) {
  const [firstName, setFistName] = useState("No Name")
  return <div>
    <br />
    <br />
    <PrimaryButton text="Primary" onClick={() => setFistName('new fist name')} />

export default simplehooks;


Events can be inline for just change the state values of it can be a separate function, in the below example code you can find both logics 

import * as React from 'react';
import { useState } from 'react';
import { ISpfxReactHooksProps } from './ISpfxReactHooksProps';
import { TextField, PrimaryButton } from 'office-ui-fabric-react';

function simplehooks(props: ISpfxReactHooksProps) {
  const [firstName, setFistName] = useState("No first Name")
  const [lastName, setLastName] = useState("No last Name")

  const _onbtnclick = () => {
    console.log('Changing value')
    setFistName('new fist name')

  const _lastNameChanged = (changedvalue: any) => {

  return (<div>
    Fullname : {firstName + ' ' + lastName}
    <br />
    <br />
    <TextField label="last name" onChanged={_lastNameChanged} value={lastName} />
    <br />
    <br />
    <PrimaryButton text="change state value" onClick={() => _onbtnclick()} />

export default simplehooks;

Async Function

In the React.Component class, we used constructor to call the async functions, in the FunctionComponent we using useEffect to replace constructor. Basically useEffect help to run the code only once while first time loads the page, If you call the async directly then it will make the infinite loop. Also while loop the elements we have to set the unique value as key as shown below example, here we setting Intex as the unique key   

import * as React from 'react';
import { useState, useEffect } from 'react';
import { ISpfxReactHooksProps } from './ISpfxReactHooksProps';
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";

function simplehooks(props: ISpfxReactHooksProps) {
  const [fruits, setfruits] = useState([])

  useEffect(() => {
      spfxContext: props.context
  }, []);

  const _getListItemsFromSP = async () => {
    const allItems: any[] = await sp.web.lists.getByTitle("Fruits").items.getAll();
    let titlevalues: string[] = [];
    allItems.forEach(function (v, i) {

  return (<div>
    { (fruit, i) {
      return <h3 key={i}>{fruit}</h3>

export default simplehooks;

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle --ship
gulp package-solution --ship

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!


Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s