How to avoid inline functions in React/Redux - reactjs

I follow a React/Redux tutorial and from what I saw on a few articles on internet I realized that inline functions are bad for performance in React.
From what I understood functions are reference type and if you use an inline function, for every re-render, this function will take a different spot in memory.
In the tutorial example I have this deleteExperience() method, that the instructor used inline.
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Moment from 'react-moment';
import { Link, withRouter } from 'react-router-dom';
import { deleteExperience } from '../../actions/profileActions';
const Experience = ({ experience, deleteExperience }) => {
const experiences = experience.map(exp => (
<tr key={exp._id}>
<td>{exp.company}</td>
<td className="hide-sm">{exp.title}</td>
<td>
<Moment format="YYYY/MM/DD">{exp.from}</Moment> -
{exp.to === null ? (
' Now '
) : (
<Moment format="YYYY/MM/DD">{exp.to}</Moment>
)}
</td>
<td>
<button className="btn btn-danger" onClick={() => deleteExperience(exp._id)}>
Delete
</button>
</td>
</tr>
));
return (
<Fragment>
<h2 className="my-2">Experience Credentials</h2>
<table className="table">
<thead>
<tr>
<th>Company</th>
<th className="hide-sm">Title</th>
<th className="hide-sm">Years</th>
<th />
</tr>
</thead>
<tbody>{experiences}</tbody>
</table>
</Fragment>
);
};
Experience.propTypes = {
experience: PropTypes.array.isRequired,
deleteExperience: PropTypes.func
};
export default connect(
null,
{deleteExperience}
)(withRouter(Experience));
So the instructor said that he used inline function
onClick={() => deleteExperience(exp._id)}
and not just called directly the function
onClick={deleteExperience(exp._id)}
to not be execute immediately.
So, please someone tell me, if the theory about bad practice to use inline function is true, how to handle this situation? I tried many ways, without any success.

The performance issue isn't from using arrow functions, but rather from creating fresh ones on every render. In your case, you can use useCallback() to memoize them. (You'll need to extract a component to render each exp object to avoid breaking the rules of hooks.) Something like this should work:
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Moment from 'react-moment';
import { Link, withRouter } from 'react-router-dom';
import { deleteExperience } from '../../actions/profileActions';
const Exp = ({ exp, deleteExperience }) => {
const del = useCallback(() => deleteExperience(exp._id), [deleteExperience, exp._id]);
return (
<tr>
<td>{exp.company}</td>
<td className="hide-sm">{exp.title}</td>
<td>
<Moment format="YYYY/MM/DD">{exp.from}</Moment> -
{exp.to === null ? (
' Now '
) : (
<Moment format="YYYY/MM/DD">{exp.to}</Moment>
)}
</td>
<td>
<button className="btn btn-danger" onClick={del}>
Delete
</button>
</td>
</tr>
);
};
const Experience = ({ experience, deleteExperience }) => {
const experiences = experience.map(exp => (
<Exp key={exp._id} exp={exp} deleteExperience={deleteExperience} />
));
return (
<Fragment>
<h2 className="my-2">Experience Credentials</h2>
<table className="table">
<thead>
<tr>
<th>Company</th>
<th className="hide-sm">Title</th>
<th className="hide-sm">Years</th>
<th />
</tr>
</thead>
<tbody>{experiences}</tbody>
</table>
</Fragment>
);
};
Experience.propTypes = {
experience: PropTypes.array.isRequired,
deleteExperience: PropTypes.func
};
export default connect(
null,
{deleteExperience}
)(withRouter(Experience));

Related

Is it possible to dipatsch on useSelector function?

Langage used : JS with REACT REDUX
The context : I have a component who render a list of quotes following the user filter and categories choice.
In my filter component, i store the select value (buttonsData), and here i re render a certains component depending on select value.
import React from 'react';
import { Table } from 'react-bootstrap';
import { useSelector } from 'react-redux';
//here each component following the user choice
import { AllForms } from './categories/AllForms';
import { AtoZ } from './sorted/AtoZ';
import { ZtoA } from './sorted/ZtoA';
import { Ascend } from './sorted/Ascend';
import CurrentOffers from './categories/CurrentOffers';
import ValidateOffers from './categories/ValidateOffers';
export const OfferList = () => {
const buttonsData = useSelector((state) => state.buttonReducer);
return (
<Table hover responsive="md" className="folder__table">
<thead className="folder__content">
<tr className="folder__titles">
<th className="folder__title"> </th>
<th className="folder__title">Order REF</th>
<th
className="folder__title"
>
Entité
</th>
<th className="folder__title">Customer</th>
<th className="folder__title">Status</th>
<th className="folder__title">Date</th>
<th className="folder__title "> </th>
</tr>
</thead>
{buttonsData.activeComponent === 'AllForms' && <AllForms />}
{buttonsData.activeComponent === 'Ascend' && <Ascend />}
{buttonsData.activeComponent === 'validate' && <ValidateOffers />}
</Table>
);
};
I have used createSelector to filter and sort my datas (working fine).
import { useSelector } from 'react-redux';
export const SelectOffersValidate = () => {
//here i select ALL my forms, get with axios
const formsDatas = useSelector((state) => state.offersReducer);
const sortedForms = [...formsDatas].filter(
(oneOffer) => oneOffer.status == 'validate'
);
console.log(sortedForms);
return sortedForms;
};
export const SelectOffersAscend = () => {
const formsDatas = useSelector((state) => state.offersReducer);
const sortedForms = [...formsDatas].sort((a, b) =>
b.createdAt.localeCompare(a.createdAt)
);
return sortedForms;
};
Here a component filtered ( i have one component for AllForms, one for Validate and one for ascend, exaclty the same but with own select function)
import React, { useState } from 'react';
import { FiEdit3 } from 'react-icons/fi';
import {
SelectOffersAscend,
} from '../../../selector/projects.selector.js';
import { isEmpty } from '../../../middlewares/verification.js';
import Moment from 'react-moment';
export const Ascend = () => {
const formsAscend = SelectOffersAscend();
return (
<>
<tbody>
{!isEmpty(formsAscend[0]) &&
formsAscend?.map((oneForm) => {
return (
<tr key={oneForm.id}>
<td>
<input
type="checkbox"
/>
</td>
<td>{oneForm.ref} </td>
<td> {oneForm.entity}</td>
<td>{oneForm.customer} </td>
<td>{oneForm.status} </td>
<td>
<Moment format="DD/MM/YYYY" date={oneForm.createdAt} />
</td>
<td>
<FiEdit3 />
</td>
</tr>
);
})}
</tbody>
</>
);
};
My first problem :
I have made a component for EACH filter, but it's repetitive, is there a better way to do ?
The second problem :
"AllForms" and "ValidateOffers" are categories and "Ascend" is a filter.
For the moment i filter only with AllForms but i would like to filtered based on categories choosen.
I've tried to create an action to store the actual categories, so i've tried to dispatch on my createSelector validate function but it's looping so i don't think is the best way to do
SOLUTION : thanks to Chris whol helped me :)
So i have delete all my filtered component to just have one and create a custom hook
import React, { useMemo } from 'react';
import { Table } from 'react-bootstrap';
import { useSelector } from 'react-redux';
import { OfferRows } from './OfferRows';
export const useFilteredOffers = () => {
const buttonsData = useSelector((state) => state.buttonReducer);
const offersData = useSelector((state) => state.offersReducer);
return useMemo(() => {
switch (buttonsData.activeComponent) {
case 'Ascend': // fix casing
return offersData?.sort((a, b) =>
b.createdAt.localeCompare(a.createdAt)
);
case 'validate':
return offersData?.filter((oneOffer) => oneOffer.status === 'validate');
case 'not validate':
return offersData?.filter(
(oneOffer) => oneOffer.status === 'not validate'
);
case 'AtoZ':
return offersData?.sort((a, b) => a.customer.localeCompare(b.customer));
case 'ZtoA':
return offersData?.sort((a, b) => b.customer.localeCompare(a.customer));
default:
return offersData;
}
}, [buttonsData.activeComponent, offersData]);
};
export const OfferList = () => {
const filteredOffers = useFilteredOffers();
return (
<Table hover responsive="md" className="folder__table">
<thead className="folder__content">
<tr className="folder__titles">
<th className="folder__title"> </th>
<th className="folder__title">Order REF</th>
<th className="folder__title">Entité</th>
<th className="folder__title">Customer</th>
<th className="folder__title">Status</th>
<th className="folder__title">Date</th>
<th className="folder__title "> </th>
</tr>
</thead>
<OfferRows offers={filteredOffers} />
</Table>
);
};
Here the rows
import React from 'react';
import { FiEdit3 } from 'react-icons/fi';
import Moment from 'react-moment';
import { isEmpty } from '../../middlewares/verification.js';
export const OfferRows = ({ offers }) => {
return (
<>
<tbody>
{!isEmpty(offers[0]) &&
offers?.map((oneForm) => {
return (
<tr key={oneForm.id}>
<td>
<input type="checkbox" />
</td>
<td>{oneForm.ref} </td>
<td> {oneForm.entity}</td>
<td>{oneForm.customer} </td>
<td>{oneForm.status} </td>
<td>
<Moment format="DD/MM/YYYY" date={oneForm.createdAt} />
</td>
<td>
<FiEdit3 />
</td>
</tr>
);
})}
</tbody>
</>
);
};
I would create a single component for the rendering of the offer rows. The data can be filtered using a single hook that also selects the active filter. You can also pass this down as an argument.
Custom hooks MUST start with the use keyword. See the Rules of Hooks documentation for more information.
const useFilteredOffers = () => {
const activeFilter = useSelector((state) => state.buttonReducer);
const offers = useSelector((state) => state.offersReducer);
return useMemo(() => {
switch (activeFilter) {
case 'Ascend': // fix casing
return offers?.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
case 'validate':
return offers?.filter(oneOffer => oneOffer.status == 'validate');
default:
return offers;
}
}, [activeFilter, offers]);
}
export const OfferList = () => {
const filteredOffers = useFilteredOffers();
return (
<Table hover responsive="md" className="folder__table">
<thead className="folder__content">
<tr className="folder__titles">
<th className="folder__title"> </th>
<th className="folder__title">Order REF</th>
<th
className="folder__title"
>
Entité
</th>
<th className="folder__title">Customer</th>
<th className="folder__title">Status</th>
<th className="folder__title">Date</th>
<th className="folder__title "> </th>
</tr>
</thead>
<OfferRows offers={filteredOffers} />
</Table>
);
};
For completeness, here is the OfferRows component.
PS: You won't need to use the isEmpty validator because Array#map won't have any effect when the Array is empty.
export const OfferRows = (offers) => {
return (
<>
<tbody>
{offers?.map((oneForm) => {
return (
<tr key={oneForm.id}>
<td>
<input
type="checkbox"
/>
</td>
<td>{oneForm.ref} </td>
<td> {oneForm.entity}</td>
<td>{oneForm.customer} </td>
<td>{oneForm.status} </td>
<td>
<Moment format="DD/MM/YYYY" date={oneForm.createdAt} />
</td>
<td>
<FiEdit3 />
</td>
</tr>
);
})}
</tbody>
</>
);
};

Frontend page doesn't display unless i comment out my table making code

Here is my code. I used typescript and my database is in a .json file. My page displays fine when I don't try to display the table and disappears completely
import React, { useState } from "react";
import "./viewAvailableShifts.css";
import "bootstrap/dist/css/bootstrap.min.css";
import MockData from "./data.json";
export class ViewAvailableShifts extends React.Component {
render() {
const [data] = useState(MockData);
return (
<>
<div className="row">
<div className="leftcolumn">
<div className="center">
<h1>Available Shifts</h1>
<div>
<table>
<thead>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
{data.map((d) => (
<tr key={d.id}>
<td>{d.first_name}</td>
<td>{d.last_name}</td>
<td>{d.email}</td>
<td>{d.gender}</td>
</tr>
))}
</tbody>
</table>
</div>
Have you tried mapping the table rows outside of the return? Also wondering why data was in square brackets? Maybe curley braces or none at all, depending on how you return it from state? so if it's already an array just data if you need to make it an array maybe spread [...data]?
export class ViewAvailableShifts extends React.Component {
render() {
const data = useState(MockData)
const rows = data.map((d) => (
<tr key={d.id}>
<td>{d.first_name}</td>
<td>{d.last_name}</td>
<td>{d.email}</td>
<td>{d.gender}</td>
</tr>
))
return (
<>
<div className="row">
<div className="leftcolumn">
<div className="center">
<h1>Available Shifts</h1>
<div>
<table>
<thead>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>{rows}</tbody>
</table>
</div>
</div>
</div>
</div>
</>
)
}
}
Hooks doesn't work inside class component
import React, { useState } from "react";
import "./viewAvailableShifts.css";
import "bootstrap/dist/css/bootstrap.min.css";
import MockData from "./data.json";
export const ViewAvailableShifts = () => {
const [data] = useState(MockData);
return (
<>
<div className="row">
<div className="leftcolumn">
<div className="center">
<h1>Available Shifts</h1>
<div>
<table>
<thead>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
{data.map((d) => (
<tr key={d.id}>
<td>{d.first_name}</td>
<td>{d.last_name}</td>
<td>{d.email}</td>
<td>{d.gender}</td>
</tr>
))}
</tbody>
</table>
</div>
What are you trying to accomplish with useState? useState is a hook that listens for changes to data and then changes the UI accordingly. Use state returns two values though, it would be used like this...
const [data, setData]= useState(someDataOrEmptyValueButNeverActuallyEmpty)
onSomeEvent((eventOrDataOrWhatNot) => setData(eventOrDataOrWhatNot))
and then whatever in your UI that was depending on data will adjust to the new values.
So, are you ready?You can't us hooks in class components
export const ViewAvailableShifts = () => {
const [data] = useState(MockData);
‏}
Should be
export default class ViewAvailableShifts extends Component {
constructor() {
super();
this.state: {data: MockData}
}
render(){...}
}

" Cannot read property 'map' of undefined"

TypeError: Cannot read property 'map' of undefined
Education
import { deleteEducation } from '../../actions/profile';
const Education = ({ education, deleteEducation }) => {
const educations = education.map(edu => (
<tr key={edu._id}>
<td>{edu.school}</td>
<td className="hide-sm">{edu.degree}</td>
<td>
here is my code of education.js
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import Moment from 'react-moment';
import moment from 'moment';
import { connect } from 'react-redux';
import { deleteEducation } from '../../actions/profile';
const Education = ({ education, deleteEducation }) => {
const educations = education.map(edu => (
<tr key={edu._id}>
<td>{edu.school}</td>
<td className="hide-sm">{edu.degree}</td>
<td>
<Moment format="YYYY/MM/DD">{moment.utc(edu.from)}</Moment> -{' '}
{edu.to === null ? (
' Now'
) : (
<Moment format="YYYY/MM/DD">{moment.utc(edu.to)}</Moment>
)}
</td>
<td>
<button
onClick={() => deleteEducation(edu._id)}
className="btn btn-danger"
>
Delete
</button>
</td>
</tr>
));
return (
<Fragment>
<h2 className="my-2">Education Credentials</h2>
<table className="table">
<thead>
<tr>
<th>School</th>
<th className="hide-sm">Degree</th>
<th className="hide-sm">Years</th>
<th />
</tr>
</thead>
<tbody>{educations}</tbody>
</table>
</Fragment>
);
};
Education.propTypes = {
education: PropTypes.array.isRequired,
deleteEducation: PropTypes.func.isRequired
};
export default connect(
null,
{ deleteEducation }
)(Education);
try this
const educations = education && education.map(edu => .....
By using this if education field not exist and empty screen display instead of error.

No access to "this"

I'm working on a web-application using the MERN stack that displays a table of clients with their name, email, and phone number. I haven't implemented Redux quite yet, but I'm using 'uuid' to supplement data in the table until I can get the redux store set up. So far I have displaying the the list and adding a client to the list working fine, but I am having trouble with the pesky delete button.
This is the current ClientTable component
import React, { Component } from "react";
import { Table, Container, Button } from "reactstrap";
import { connect } from "react-redux";
import {
getClients,
addClient,
editClient,
deleteClient,
} from "../actions/clientActions";
import PropTypes from "prop-types";
const renderClient = (clients, index, id) => {
return (
<tr key={index}>
<td>
<Button
className="remove-btn"
color="danger"
size="sm"
onClick={() => {
this.setState((state) => ({
clients: state.clients.filter((client) => client.id !== id),
}));
}}
>
×
</Button>
</td>
<td>{clients.name}</td>
<td>{clients.email}</td>
<td>{clients.number}</td>
</tr>
);
};
class ClientTable extends Component {
componentDidMount() {
this.props.getClients();
}
onDeleteClick = (id) => {
this.props.deleteClient(id);
};
render() {
const { clients } = this.props.client;
// const { clients } = this.state;
return (
<Container id="listContainer">
<Table
id="listTable"
className="table-striped table-bordered table-hover"
dark
>
<tr class="listRow">
<thead id="tableHeader">
<tr>
<th id="listActions">Actions</th>
<th id="listName">Name</th>
<th id="listEmail">Email</th>
<th id="listNumber">Number</th>
</tr>
</thead>
<tbody class="listRow">{clients.map(renderClient)}</tbody>
</tr>
</Table>
</Container>
);
}
}
ClientTable.propTypes = {
getClients: PropTypes.func.isRequired,
client: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
client: state.client,
});
export default connect(mapStateToProps, {
getClients,
deleteClient,
addClient,
})(ClientTable);
This is the bit of code that is causing me issues
<Button
className="remove-btn"
color="danger"
size="sm"
onClick={() => {
this.setState((state) => ({
clients: state.clients.filter((client) => client.id !== id),
}));
}}
>
×
</Button>
When I click the "delete" button I keep getting TypeError: Cannot read property 'setState' of unedefined
I know the error is because of 'this' isn't bound to anything, but I'm uncertain how to bind it within an onClick event if that is even possible or what even to bind it to. I am just lost as to how to approach this problem. (I'm still quite new to React).
If anyone has any ideas it would be greatly appreciated!
move renderClient function to ClientTable, and use it as a method of this class.
class ClientTable extends Component {
componentDidMount() {
this.props.getClients();
}
renderClient = (clients, index) => {
return (
<tr key={index}>
<td>
<Button
className="remove-btn"
color="danger"
size="sm"
onClick={() => this.onDeleteClient(clients.id)}
>
×
</Button>
</td>
<td>{clients.name}</td>
<td>{clients.email}</td>
<td>{clients.number}</td>
</tr>
);
};
onDeleteClick = (id) => {
this.props.deleteClient(id);
};
render() {
const { clients } = this.props.client;
// const { clients } = this.state;
return (
<Container id="listContainer">
<Table
id="listTable"
className="table-striped table-bordered table-hover"
dark
>
<tr class="listRow">
<thead id="tableHeader">
<tr>
<th id="listActions">Actions</th>
<th id="listName">Name</th>
<th id="listEmail">Email</th>
<th id="listNumber">Number</th>
</tr>
</thead>
<tbody class="listRow">{clients.map(this.renderClient)}</tbody>
</tr>
</Table>
</Container>
);
}
}

Redux: using different reducers for a component

I've got a component UsersList which I'd like to reuse with two different reducers - one for listing regular users (state.users.x) and one for listing administrators (state.adminusers.x). The display is the same in both cases, but the state is in different places and different api actions apply (different endpoints with different business rules).
How can I write my component so it can use either reducer?
Write the UsersList component as normal, but do not connect it to redux.
For example:
import React, { Component } from 'react';
import { Table } from 'react-bootstrap';
import UserInviteRow from 'jsx/components/Lib/Users/UserInviteRow';
export class UsersList extends Component {
render() {
const { inviteUserToOrg } = this.props;
return (
<Table bordered hover>
<thead>
<tr>
<th className="width-200">First Name</th>
<th className="width-250">Last Name</th>
<th>Email</th>
<th className="width-150">Last Login</th>
<th className="width-100"> </th>
</tr>
</thead>
<tbody>
<UserInviteRow invitefxn={ inviteUserToOrg }/>
{ this.renderRows() }
</tbody>
</Table>
);
}
renderRows() {
const { usersList } = this.props;
if( ! usersList.length ) {
return (
<tr>
<td colSpan="5">
<em>No users exist for this non-profit</em>
</td>
</tr>
);
}
return usersList.map( (user) => {
return (
<tr key={user.key}>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
<td>{user.correspondenceEmailAddress}</td>
<td>{ (user.lastSeen) ? formatTime(user.lastSeen) : '' }</td>
<td className="text-center">
{ this.renderRemoveButton( user ) }
</td>
</tr>
);
});
}
renderRemoveButton(user) {
const { currentUser } = this.props;
if( currentUser.key === user.key ) {
// users cannot remove themselves
return null;
}
return (
<a className="text-danger" onClick={ () => { this.removeUser(user) } }>
<em className="fa fa-times" />
</a>
);
}
removeUser( user ) {
this.props.removeUserFromOrg(user.key);
}
}
export default UsersList;
Make sure both your reducers implement the action functions you use, in this case inviteUserToOrg and removeUserFromOrg.
Create new container components connected to each reducer
For example:
import { connect } from 'react-redux';
import {
inviteUserToOrg,
removeUserFromOrg
} as actions from 'jsx/redux/modules/nonadminUsers';
import UsersList from 'jsx/components/Lib/Users/UsersList';
var NonadminUserList = connect(
state => {
return {
usersList: state.users.usersList,
};
},
actions
)(UsersList);
export default NonadminUserList;
and
import { connect } from 'react-redux';
import {
inviteUserToOrg,
removeUserFromOrg
} as actions from 'jsx/redux/modules/adminUsers';
import UsersList from 'jsx/components/Lib/Users/UsersList';
var AdminUserList = connect(
state => {
return {
usersList: state.adminusers.usersList,
};
},
actions
)(UsersList);
export default AdminUserList;
Now changes to your presentation component, UsersList, will affect both container components and each container component can reference it's own reducer state and actions.

Resources