Hooks Overview
React Hooks are a way to add React.Component features to functional components. This includes features such as:
Hooks allow you to use React's features without classes.
What is this useState() syntax?
You may be unfamiliar with the useState() syntax. This syntax uses a destructuring assignment for arrays. The principle is similar to how we would pull props out an object with object destructuring.
What does useState() give us?
UseState gives us two variables. We can name our two variables whatever we want, just know that
- The first variable is the value. Similar to this.state
- The second variable is a function to update that value. Similar to this.setState
- The final part of useState is the argument that we pass to it. The useState argument is the initial state value. In the case of our counter, we started at 0.
What's wrong with classes?
The React Hooks intro gives a good section on this: Classes confuse both people and machines. Essentially, classes can sometimes be confusing and be written in any number of ways. Dive into somebody else's project and you could be in for a world of different syntax and style choices. There are no plans to remove class support, we just have another way to code. By allowing classes to be converted into smaller functional components, we can break out parts of our application into smaller and more focused components.
React's Effect Hook
The State Hook allows us to use state in React functional components. This gets us a step closer to using functional components over class components. The next part of moving to functional components is lifecycle methods. Effects are similar to componentDidMount, componentDidUpdate, and componentWillUnmount. This is what the Effect Hook is for. Furthermore, side-effects are things you want your application to make. These include:
- Fetching data
- Manually changing the DOM (document title)
- Setting up a subscription
- Effects will run after every render, including the first render.
Running an Effect Hook only when something changes
Since useEffect() runs every time a component renders, how do we get it to run only once on mount? The Effect Hook can take a second argument, an array. It will look through the array and only run the effect if one of those values has changed.
- componentDidMount: Runs once
-
- useEffect(() => {
-
- }, []);
- componentDidUpdate: Runs on changes
-
- useEffect(
- () => {
-
- },
- [count]
- );
What about componentWillUnmount()
To run something before a component unmounts, we just have to return a function from useEffect()
Using State and Effects Together
There's no problem using them together! Together they can create functional components that work the same as your class components!
Open a command prompt. Create a directory for SPFx solution.
md spfx-React-Hooks
Navigate to the above-created directory.
cd spfx-React-Hooks
Run the Yeoman SharePoint Generator to create the solution.
yo @microsoft/sharepoint
Solution Name
Hit Enter for a default name (spfx-pnp-DropDown in this case) or type in any other name for your solution.
Selected choice - Hit Enter
Target for the component
Here, we can select the target environment where we are planning to deploy the client web part, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest)
Place of files
We may choose to use the same folder or create a subfolder for our solution.
Selected choice - Same folder
Deployment option
Selecting Y will allow the app to deployed instantly to all sites and will be accessible everywhere.
Selected choice - N (install on each site explicitly)
Permissions to access web APIs
Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.
Selected choice - N (solution contains unique permissions)
Type of client-side component to create
We can choose to create a client-side web part or an extension. Choose web part option.
Selected choice - WebPart
Web part name
Hit Enter to select the default name or type in any other name.
Selected choice - SpfxReactHooksCrud
Web part description
Hit Enter to select the default description or type in any other value.
Framework to use
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice - React
Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
Once the scaffolding process is completed, lock down the version of project dependencies by running below command.
npm shrinkwrap
In the command prompt, type below command to open the solution in the code editor of your choice.
code .
NPM Packages Used,
On the command prompt, run below command.
npm i @pnp/logging @pnp/common @pnp/odata @pnp/sp --save
for Pollyfills
npm install --save @pnp/polyfill-ie11
in SpfxReactHooksCrudWebPart.ts,
- import * as React from 'react';
- import * as ReactDom from 'react-dom';
- import { Version } from '@microsoft/sp-core-library';
- import {
- BaseClientSideWebPart,
- IPropertyPaneConfiguration,
- PropertyPaneTextField
- } from '@microsoft/sp-webpart-base';
-
- import * as strings from 'SpfxReactHooksCrudWebPartStrings';
- import SpfxReactHooksCrud from './components/SpfxReactHooksCrud';
- import { ISpfxReactHooksCrudProps } from './components/ISpfxReactHooksCrudProps';
- import "@pnp/polyfill-ie11";
- import { sp, Web } from '@pnp/sp';
-
- export interface ISpfxReactHooksCrudWebPartProps {
- description: string;
- }
-
- export default class SpfxReactHooksCrudWebPart extends BaseClientSideWebPart<ISpfxReactHooksCrudWebPartProps> {
- protected onInit(): Promise<void> {
- return new Promise<void>((resolve: () => void, reject: (error?: any) => void): void => {
- sp.setup({
- sp: {
- headers: {
- "Accept": "application/json; odata=nometadata"
- }
- }
- });
- resolve();
- });
- }
- public render(): void {
- const element: React.ReactElement<ISpfxReactHooksCrudProps > = React.createElement(
- SpfxReactHooksCrud,
- {
- description: this.properties.description,
- context: this.context
- }
- );
-
- ReactDom.render(element, this.domElement);
- }
-
- protected onDispose(): void {
- ReactDom.unmountComponentAtNode(this.domElement);
- }
-
- protected get dataVersion(): Version {
- return Version.parse('1.0');
- }
-
- protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
- return {
- pages: [
- {
- header: {
- description: strings.PropertyPaneDescription
- },
- groups: [
- {
- groupName: strings.BasicGroupName,
- groupFields: [
- PropertyPaneTextField('description', {
- label: strings.DescriptionFieldLabel
- })
- ]
- }
- ]
- }
- ]
- };
- }
- }
in HookUsestate.ts
- export interface IHooksuseState {
- MileStone?:any;
- Id?:any;
- Title?:any;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
in ISpfxReactHooksCrudProps.ts- import {WebPartContext} from '@microsoft/sp-webpart-base';
- export interface ISpfxReactHooksCrudProps {
- description: string;
- context: WebPartContext;
- }
in SpfxReactHooksCrud.tsx- import * as React from 'react';
-
- import { ISpfxReactHooksCrudProps } from './ISpfxReactHooksCrudProps';
- import { escape } from '@microsoft/sp-lodash-subset';
- import { MyListComponent } from './MyList';
- const UserContext = React.createContext([]);
- export default class SpfxReactHooksCrud extends React.Component<ISpfxReactHooksCrudProps, {}> {
- public render(): React.ReactElement<ISpfxReactHooksCrudProps> {
- return (
- <div >
- <MyListComponent />
- </div>
- );
- }
- }
in MyList.tsx- import * as React from 'react';
- import { SpListCollection } from './mySpListCollection';
-
- export const MyListComponent = () => {
- const { datacol, loaddata } = SpListCollection();
- React.useEffect(() => {
- loaddata();
- }, []);
- return (
- <div>
- <DataBinding DataNewCol={datacol} />
-
- </div>
- );
- };
- const DataBinding = (props) => {
-
- const DataNewCol = props.DataNewCol;
- const listItems = DataNewCol.map((data, index) =>
- <div key={index}>
- <h3>{data.Title}</h3>
- <p>{data.MileStone}</p>
- <p>{data.Id}</p>
- </div>
- );
- return (
- <div>{listItems}</div>
- );
- };
in mySpListCOllection.tsx- import * as React from 'react';
- import { sp } from "@pnp/sp";
- import { IHooksuseState } from './HooksuseState';
- export const SpListCollection = () => {
- const [datacol, setdatacol] = React.useState([]);
- const loaddata = () => {
- sp.web.lists.getByTitle("ProjectStatus").items.select('Title', 'Id', 'MileStone').get().then((items) => {
- let result: IHooksuseState[] = [];
- items.forEach(element => {
- result.push({
- Id: element.Id, Title: element.Title, MileStone: element.MileStone
- });
- });
- return result;
- }) .then(resultdata => setdatacol(resultdata));
- };
- return { datacol, loaddata, setdatacol };
- };
Here I am using "ProjectStatus" as a list name with "MileStone,Id,Title" as Field Names. For details visit
React-Hooks
Happy Coding:)