Can I safe navigate within useMemo - javascript

Can I use the && style safe navigation or lodash get in useMemo's second parameter like this:
useMemo(() => {
return {
...
}
}, [state && state.data]) // or with lodash: get(state, 'data')

Yes, but not without warning.
React Hook useMemo has a complex expression in the dependency array.
Extract it to a separate variable so it can be statically checked.
(react-hooks/exhaustive-deps)eslint
export default function App() {
const [state, setState] = useState({ data: 'foobar' });
const memoizedState = useMemo(() => {
return state.data + state.data;
}, [state && state.data]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>{memoizedState}</h2>
</div>
);
}
Better solution would be to factor it into a single variable as suggested, or use the entire state value and handle it internally. Keep in mind the more you minimize the surface area of reference mutations then the more stable your memoized value will be.
If you are certain a state value like this will always have that shape, then I think you can safely use state.data as a dependency.
I generally prefer NOT to use complex objects in react useState hooks (you certainly can) and will break the object properties into their own state hooks. This allows you to update "parts" of your state without mutating references to the rest. This is especially advantageous in situations like yours where maybe you're not sure state.a.b.c.data is a complete and valid defined object reference. Or some other hooks depend only on part of your component state.

Related

Using Variable from Props vs Passing Prop as Argument in React

In terms of writing components, which would be the preferred way to write below component? Assume that removeCard is outside of shown scope, ie. redux action.
My assumption would be that ComponentCardB would be, as it avoids passing an unnecessary argument which would be in the scope anyway. I imagine in terms of performance in the grand scheme of things, the difference is negligible, just more of a query in regards to best practise.
TIA
const ComponentCardA = (id) => {
const handleRemove = (cardId) => {
removeCard(cardId);
};
<div onClick={() => handleRemove(id)} />;
};
const ComponentCardB = (id) => {
const handleRemove = () => {
removeCard(id);
};
<div onClick={handleRemove} />;
};
With functional components like that, yes, there's no reason for the extra layer of indirection in ComponentCardA vs ComponentCardB.
Slightly tangential, but related: Depending on what you're passing handleRemove to and whether your component has other props or state, you may want to memoize handleRemove via useCallback or useMemo. The reason is that if other props or state change, your component function will get called again and (with your existing code) will create a new handleRemove function and pass that to the child. That means that the child has to be updated or re-rendered. If the change was unrelated to id, that update/rerender is unnecessary.
But if the component just has id and no other props, there's no point, and if it's just passing it to an HTML element (as opposed to React component), there's also probably no point as updating that element's click handler is a very efficient operation.
The second option is better way because using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison.
Also if you don't want to use syntax with props.id you rather create function component with object as parameter:
const Component = ({id}) => { /* ... */ }
Of course using arrow function is also allowed but remember, when you don't have to use them then don't.

how to use react memo

I am trying to make a simple task manager app and I want to implement react memo in TaskRow (task item) but when I click the checkbox to finish the task, the component properties are the same and I cannot compare them and all tasks are re-rendered again, any suggestions? Thanks
Sand Box: https://codesandbox.io/s/interesting-tharp-ziwe3?file=/src/components/Tasks/Tasks.jsx
Tasks Component
import React, { useState, useEffect, useCallback } from 'react'
import TaskRow from "../TaskRow";
function Tasks(props) {
const [taskItems, setTaskItems] = useState([])
useEffect(() => {
setTaskItems(JSON.parse(localStorage.getItem('tasks')) || [])
}, [])
useEffect(() => {
if (!props.newTask) return
newTask({ id: taskItems.length + 1, ...props.newTask })
}, [props.newTask])
const newTask = (task) => {
updateItems([...taskItems, task])
}
const toggleDoneTask = useCallback((id) => {
const taskItemsCopy = [...taskItems]
taskItemsCopy.map((t)=>{
if(t.id === id){
t.done = !t.done
return t
}
return t
})
console.log(taskItemsCopy)
console.log(taskItems)
updateItems(taskItemsCopy)
}, [taskItems])
const updateItems = (tasks) => {
setTaskItems(tasks)
localStorage.setItem('tasks', JSON.stringify(tasks))
}
return (
<React.Fragment>
<h1>learning react </h1>
<table>
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Done</th>
</tr>
</thead>
<tbody>
{
props.show ? taskItems.map((task, i) =>
<TaskRow
task={task}
key={task.id}
toggleDoneTask={()=>toggleDoneTask(task.id)}>
</TaskRow>)
:
taskItems.filter((task) => !task.done)
.map((task) =>
<TaskRow
show={props.show}
task={task}
key={task.id}
toggleDoneTask={()=>toggleDoneTask(task.id)}></TaskRow>
)
}
</tbody>
</table>
</React.Fragment>
)
}
export default Tasks
Item task (TaskRow component)
import React, { memo } from 'react'
function TaskRow(props) {
return (<React.Fragment>
{console.log('render', props.task)}
<Tr show={props.show} taskDone={props.task.done}>
<td>
{props.task.title}
</td>
<td>
{props.task.description}
</td>
<td>
<input type="checkbox"
checked={props.task.done}
onChange={props.toggleDoneTask}
/>
</td>
</Tr>
</React.Fragment>)
}
export default memo(TaskRow, (prev,next)=>{
console.log('prev props', prev.task)
console.log('next props', next.task)
})
I'm afraid there are quite a lot of problems with the code you've shared, only some of them due to React.memo. I'll start there and work through the ones I've spotted.
You've provided an equality testing function to memo, but you are not using it to test anything. The default behaviour, which requires no testing function, will shallowly compare props between the previous and the next render. This means it will pick up on differences between primitive values (e.g. string, number, boolean) and references to objects (e.g. literals, arrays, functions), but it will not automatically deeply compare those objects.
Remember, memo will only allow rerenders when the equality testing function returns false. You've provided no return value to the testing function, meaning it returns undefined, which is falsy. I've provided a simple testing function for an object literal with primitive values which will do the job needed here. If you have more complex objects to pass in the future, I suggest using a comprehensive deep equality checker like the one provided by the lodash library, or, even better, do not pass objects at all if you can help it and instead try to stick to primitive values.
export default memo(TaskRow, (prev, next) => {
const prevTaskKeys = Object.keys(prev.task);
const nextTaskKeys = Object.keys(next.task);
const sameLength = prevTaskKeys.length === nextTaskKeys.length;
const sameEntries = prevTaskKeys.every(key => {
return nextTaskKeys.includes(key) && prev.task[key] === next.task[key];
});
return sameLength && sameEntries;
});
While this solves the initial memoisation issue, the code is still broken for a couple of reasons. The first is that despite copying your taskItems in toggleTaskDone, for similar reasons to those outlined above, your array of objects is not deeply copied. You are placing the objects in a new array, but the references to those objects are preserved from the previous array. Any changes you make to those objects will be directly mutating the React state, causing the values to become out of sync with the rest of your effects.
You can solve this by mapping the copy and spreading the objects. You would have to do this for every level of object reference in any state object you attempt to change, which is part of the reason that React advises against complex objects in useState (one level of depth is usually fine).
const taskItemsCopy = [...taskItems].map((task) => ({ ...task }));
Side Note: You are not doing anything with the result of taskItemsCopy in your original code. map is not a mutating method - calling it without assigning the result to a variable does nothing.
The next issue is more subtle, and demonstrates one of the pitfalls and potential complications when memoising your components. The toggleTaskDone callback has taskItems in its dependency array. However, you are passing it as a prop in an anonymous function to TaskRow. This prop is not being considered by React.memo - we're specifically ignoring it because we only want to rerender on changes to the task object itself. This means that when a task does change its done status, all the other tasks are becoming out of sync with the new value of taskItems - when they change their done status, they will be using the value of taskItems as it was the last time they were rendered.
Inline anonymous functions are recreated on every render, so they are always unequal by reference. You could actually fix this somewhat by adjusting the way the callback is passed and executed:
// Tasks.jsx
toggleDoneTask={toggleDoneTask}
// TaskRow.jsx
onChange={() => props.toggleDoneTask(props.task.id)}
In this way you would be able to check for reference changes in your memo equality function, but since the callback changes every time taskItems changes, this would make the memoisation completely useless!
So, what to do. This is where the implementation of the rest of the Tasks component starts to limit us a bit. We can't have taskItems in the dependency of toggleTaskDone, and we also can't call updateItems because that has the same (implicit) dependency. I've provided a solution which technically works, although I would consider this a hack and not really recommended for actual usage. It relies on the callback version of setState which will allow us to have access to the current value of taskItems without including it as a dependency.
const toggleDoneTask = useCallback((id) => {
setTaskItems((prevItems) => {
const prevCopy = [...prevItems].map((task) => ({ ...task }));
const newItems = prevCopy.map((t) => {
if (t.id === id) t.done = !t.done;
return t;
});
localStorage.setItem("tasks", JSON.stringify(newItems));
return newItems;
});
}, []);
Now it doesn't matter that we aren't equality checking the handler prop, because the function never alters from the initial render of the component. With these changes implemented my fork of your sandbox seems to be working as expected.
On a broader note, I really think you should consider writing React code using create-react-app when you're learning the framework. I was a little surprised to see you had a custom webpack set up, and you don't seem to have proper linting for React (bundled automatically in CRA) which would highlight a lot of these issues for you as warnings. Specifically, the misuse of the dependency array in a number of places in the Task component which is going to make it unstable and error prone even with the essential fixes I've suggested.

Is the old `setX` value from `useState` still valid after the state is updated? [duplicate]

Is useState's setter able to change during a component life ?
For instance, let's say we've got a useCallback which will update the state.
If the setter is able to change, it must be set as a dependency for the callback since the callback use it.
const [state, setState] = useState(false);
const callback = useCallback(
() => setState(true),
[setState] // <--
);
The setter function won't change during component life.
From Hooks FAQ:
(The identity of the setCount function is guaranteed to be stable so it’s safe to omit.)
The setter function (setState) returned from useState changes on component re-mount, but either way, the callback will get a new instance.
It's a good practice to add state setter in the dependency array ([setState]) when using custom-hooks. For example, useDispatch of react-redux gets new instance on every render, you may get undesired behavior without:
// Custom hook
import { useDispatch } from "react-redux";
export const CounterComponent = ({ value }) => {
// Always new instance
const dispatch = useDispatch();
// Should be in a callback
const incrementCounter = useCallback(
() => dispatch({ type: "increment-counter" }),
[dispatch]
);
return (
<div>
<span>{value}</span>
// May render unnecessarily due to the changed reference
<MyIncrementButton onIncrement={dispatch} />
// In callback, all fine
<MyIncrementButton onIncrement={incrementCounter} />
</div>
);
};
The short answer is, no, the setter of useState() is not able change, and the React docs explicitly guarantee this and even provide examples proving that the setter can be omitted.
I would suggest that you do not add anything to the dependencies list of your useCallback() unless you know its value can change. Just like you wouldn't add any functions imported from modules or module-level functions, constant expressions defined outside the component, etc. adding those things is just superfluous and makes it harder to read your handlers.
All that being said, this is all very specific to the function that is returned by useState() and there is no reason to extend that line of reasoning to every possible custom hook that may return a function. The reason is that the React docs explicitly guarantee the stable behavior of useState() and its setters, but it does not say that the same must be true for any custom hook.
React hooks are still kind of a new and experimental concept and we need to make sure we encourage each other to make them as readable as possible, and more importantly, to understand what they actually do and why. If we don't it will be seen as evidence that hooks are a "bad idea," which will prohibit adoption and wider understanding of them. That would be bad; in my experience they tend to produce much cleaner alternatives to the class-based components that React is usually associated with, not to mention the fact that they can allow organizational techniques that simply aren't possible with classes.

Should I use useselector/useDispatch instead of mapStateToProps

When creating a React app, if I use the hook useSelector, I need to adhere to the hooks invoking rules (Only call it from the top level of a functional component). If I use the mapStateToProps, I get the state in the props and I can use it anywhere without any issues... Same issue for useDispatch
What are the benefits of using the hook besides saving lines of code compared to mapStateToProps?
Redux store state can be read and changed from anywhere in the component, including callbacks. Whenever the store state is changed the component rerenders. When the component rerenders, useSelector runs again, and gives you the updated data, later to be used wherever you want. Here is an example of that and a usage of useDispatch inside a callback (after an assignment in the root level):
function Modal({ children }) {
const isOpen = useSelector(state => state.isOpen);
const dispatch = useDispatch();
function handleModalToggeled() {
// using updated data from store state in a callback
if(isOpen) {
// writing to state, leading to a rerender
dispatch({type: "CLOSE_MODAL"});
return;
}
// writing to state, leading to a rerender
dispatch({type: "OPEN_MODAL"});
}
// using updated data from store state in render
return (isOpen ? (
<div>
{children}
<button onClick={handleModalToggeled}>close modal</button>
</div>
) : (
<button onClick={handleModalToggeled}>open modal</button>
);
);
}
There is nothing you can do with mapStateToProps/mapDispatchToProps that you can't do with the useSelector and useDispatch hooks as well.
With that said, there are a couple of differences between the two methods that are worth considering:
Decoupling: with mapStateToProps, container logic (the way store data is injected into the component) is separate from the view logic (component rendering).
useSelector represents a new and different way of thinking about connected components, arguing that the decoupling is more important between components and that components are self contained. Which is better? Verdict: no clear winner. source
DX (Developer experience): using the connect function usually means there should be another additional container component for each connected component, where using the useSelector and useDispatch hooks is quite straightforward. Verdict: hooks have better DX.
"Stale props" and "Zombie child": there are some weird edge cases with useSelector, if it depends on props, where useSelector can run before the newest updated props come in. These are mostly rare and avoidable edge cases, but they had been already worked out in the older connect version. verdict: connect is slightly more stable than hooks. source
Performance optimizations: both support performance optimizations in different ways: connect has some advanced techniques, using merge props and other options hidden in the connect function. useSelector accepts a second argument - an equality function to determine if the state has changed. verdict: both are great for performance in advanced situations.
Types: using typescript with connect is a nightmare. I remember myself feverishly writing three props interfaces for each connected component (OwnProps, StateProps, DispatchProps). Redux hooks support types in a rather straightforward way. verdict: types are significantly easier to work with using hooks.
The future of React: Hooks are the future of react. This may seam like an odd argument, but change to the ecosystem is right around the corner with "Concurrent mode" and "Server components". While class components will still be supported in future React versions, new features may rely solely on hooks. This change will of course also affect third party libraries in the eco system, such as React-Redux. verdict: hooks are more future proof.
TL;DR - Final verdict: each method has its merits. connect is more mature, has less potential for weird bugs and edge cases, and has better separation of concerns. Hooks are easier to read and write, as they are collocated near the place where they are used (all in one self contained component). Also, they are easier to use with TypeScript. Finally, they will easily be upgradable for future react versions.
I think you misunderstand what "top level" is. It merely means that, inside a functional component, useSelector() cannot be placed inside loops, conditions and nested functions. It doesn't have anything to do with root component or components structure
// bad
const MyComponent = () => {
if (condition) {
// can't do this
const data = useSelector(mySelector);
console.log(data);
}
return null;
}
---
// good
const MyComponent = () => {
const data = useSelector(mySelector);
if (condition) {
console.log(data); // using data in condition
}
return null;
}
If anything, mapStateToPtops is located at even higher level than a hook call
the rules of hooks make it very hard to use that specific hook. You still need to somehow access a changing value from the state inside callbacks
To be fair you almost never have to access changing value inside a callback. I can't remember last time I needed that. Usually if your callback needs the latest state, you are better off just dispatching an action and then handler for that action (redux-thunk, redux-saga, redux-observable etc) will itself access the latest state
This is just specifics of hooks in general (not just useSelector) and there are tons of ways to go around it if you really want to, for example
const MyComponent = () => {
const data = useSelector(mySelector);
const latestData = useRef()
latestData.current = data
return (
<button
onClick={() => {
setTimeout(() => {
console.log(latestData.current) // always refers to latest data
}, 5000)
}}
/>
)
}
What are the benefits of using the hook besides saving lines of code compared to mapStateToProps?
You save time by not writing connect function any time you need to access store, and removing it when you no longer need to access store. No endless wrappers in react devtools
You have clear distinction and no conflicts between props coming from connect, props coming from parent and props injected by wrappers from 3rd party libraries
Sometimes you (or fellow developers you work with) would choose unclear names for props in mapStateToProps and you will have to scroll all the way to mapStateToProps in the file to find out which selector is used for this specific prop. This is not the case with hooks where selectors and variables with data they return are coupled on the same line
By using hooks you get general advantages of hooks, the biggest of which is being able couple together and reuse related stateful logic in multiple components
With mapStateToProps you usually have to deal with mapDispatchToProps which is even more cumbersome and easier to get lost in, especially reading someone else's code (object form? function form? bindActionCreators?). Prop coming from mapDispatchToProps can have same name as it's action creator but different signature because it was overridden in mapDispatchToprops. If you use one action creator in a number of components and then rename that action creator, these components will keep using old name coming from props. Object form easily breaks if you have a dependency cycle and also you have to deal with shadowing variable names
.
import { getUsers } from 'actions/user'
class MyComponent extends Component {
render() {
// shadowed variable getUsers, now you either rename it
// or call it like this.props.getUsers
// or change import to asterisk, and neither option is good
const { getUsers } = this.props
// ...
}
}
const mapDispatchToProps = {
getUsers,
}
export default connect(null, mapDispatchToProps)(MyComponent)
See EDIT 2 at the end for the final answer
Since no one knows how to answer, it seems like the best answer is that you should NOT be using useselector when you need information in other places other than the root level of your component. Since you don't know if the component will change in the future, just don't use useselector at all.
If someone has a better answer than this, I'll change the accepted answer.
Edit: Some answers were added, but they just emphasize why you shouldn't be using useselector at all, until the day when the rules of hooks will change, and you'll be able to use it in a callback as well. That being said, if you don't want to use it in a callback, it could be a good solution for you.
EDIT 2: An answer with examples of all that I wanted was added and showed how useSelector and useDispatch are easier to use.
The redux state returned from the useSelector hook can be passed around anywhere else just like its done for mapStateToProps. Example: It can be passed to another function too. Only constraint being that the hook rules has to be followed during its declaration:
It has to be declared only within a functional component.
During declaration, it can not be inside any conditional block . Sample code below
function test(displayText) {
return (<div>{displayText}</div>);
}
export function App(props) {
const displayReady = useSelector(state => {
return state.readyFlag;
});
const displayText = useSelector(state => {
return state.displayText;
});
if(displayReady) {
return
(<div>
Outer
{test(displayText)}
</div>);
}
else {
return null;
}
}
EDIT: Since OP has asked a specific question - which is about using it within a callback, I would like to add a specific code.In summary, I do not see anything that stops us from using useSelector hook output in a callback. Please see the sample code below, its a snippet from my own code that demonstrates this particular use case.
export default function CustomPaginationActionsTable(props) {
//Read state with useSelector.
const searchCriteria = useSelector(state => {
return state && state.selectedFacets;
});
//use the read state in a callback invoked from useEffect hook.
useEffect( ()=>{
const postParams = constructParticipantListQueryParams(searchCriteria);
const options = {
headers: {
'Content-Type': 'application/json'
},
validateStatus: () => true
};
var request = axios.post(PORTAL_SEARCH_LIST_ALL_PARTICIPANTS_URI, postParams, options)
.then(function(response)
{
if(response.status === HTTP_STATUS_CODE_SUCCESS) {
console.log('Accessing useSelector hook output in axios callback. Printing it '+JSON.stringify(searchCriteria));
}
})
.catch(function(error) {
});
}, []);
}
For callback functions you can use the value returned from useSelector the same way you would use the value from useState.
const ExampleComponent = () => {
// use hook to get data from redux state.
const stateData = useSelector(state => state.data);
// use hook to get dispatch for redux store.
// this allows actions to be dispatched.
const dispatch = useDispatch();
// Create a non-memoized callback function using stateData.
// This function is recreated every rerender, a change in
// state.data in the redux store will cause a rerender.
const callbackWithoutMemo = (event) => {
// use state values.
if (stateData.condition) {
doSomething();
}
else {
doSomethingElse();
}
// dispatch some action to the store
// can pass data if needed.
dispatch(someActionCreator());
};
// Create a memoized callback function using stateData.
// This function is recreated whenever a value in the
// dependency array changes (reference comparison).
const callbackWithMemo = useCallback((event) => {
// use state values.
if (stateData.condition) {
doSomething();
}
else {
doSomethingElse();
}
// dispatch some action to the store
// can pass data if needed.
dispatch(someActionCreator());
}, [stateData, doSomething, doSomethingElse]);
// Use the callbacks.
return (
<>
<div onClick={callbackWithoutMemo}>
Click me
</div>
<div onClick={callbackWithMemo}>
Click me
</div>
</>
)
};
Rules of hooks says you must use it at the root of your component, meaning you CANT use it anywhere.
As Max stated in his answer just means that the hook statement itself must not be dynamic / conditional. This is because the order of the base hooks (react's internal hooks: useState, etc) is used by the backing framework to populate the stored data each render.
The values from hooks can be used where ever you like.
While I doubt this will be close to answering your complete question, callbacks keep coming up and no examples had been posted.
not the answer but this hook can be very helpful if you want to get decoupled nature of mapDispatchToProps while keeping simplicity and dev experience of hooks:
https://gist.github.com/ErAz7/1bffea05743440d6d7559afc9ed12ddc
the reason I don't mention one for mapStatesToProps is that useSelector itself is more store-logic-decoupling than mapStatesToProps so don't see any advantage for mapStatesToProps. Of course I dont mean using useSelector directly but instead create a wrapper on it in your store files (e.g. in reducer file) and import from there, like this:
// e.g. userReducer.js
export const useUserProfile = () => useSelector(state => state.user.profile)

Correct way to use immutablejs (toJS and fromJS) with redux

I wonder if this is a correct way to use immutable.js with redux and reselect (also redux-saga). Specifically I wonder about toJS() and from fromJS() and where to use them.
My idea is that:
I use toJS() when sending data to a saga.
I do not use fromJS() in reducer because I think that it is done anyway by the fact that I use fromJS() for initialState. Or am I wrong about that?
I use toJS() in selector from reselect so I can use js data in react component.
Example:
1) In my react component I do:
// mapDispatchToProps
function mapDispatchToProps(dispatch) {
return {
loginRequest: values => dispatch(loginRequest(values)),
};
}
// Sending values.toJS() to my redux-saga.
submit = values => {
this.props.loginRequest(values.toJS());
};
2) In reducer I do (should one use fromJS() here or not? According to redux docs you should):
const { fromJS } = require('immutable');
const state = fromJS({
pages: {
usersPage: {
loading: false,
isFetched: false,
list: [],
}
}
});
function reducer(state, action) {
switch(action.type) {
case 'USERS_LOADED':
return state
.setIn(['usersPage', 'list'], action.payload) // fromJS() here or not?
.setIn(['usersPage', 'isFetched'], true)
.setIn(['usersPage', 'loading'], false)
;
default:
return state;
}
}
export default reducer;
3) In my selector I do toJS() again:
const selectUser = state => state.get('user', initialState);
const makeSelectList= () =>
createSelector(selectUser, userState => userState.getIn(['usersPage',
'list']).toJS());
// Which I then use in my react component:
const mapStateToProps = createStructuredSelector({
list: makeSelectList(),
});
So basically I wonder if that is a correct flow of convertion between js and immutable. Or can it be optimized in some way (less convertion steps)? Maybe the above is a non-optimal way of logic?
Best Regards
The saga--being redux middleware--can handle Immutable types directly, no need to use an expensive toJS call here
Any point you're converting (e.g. set, setIn, update, etc) a plain JS non-simple type into the Immutable redux state tree, use fromJS to ensure a fully Immutable type Make entire state tree immutable
IMHO, selectors (e.g. reselect)--by providing memoization after the initial retrieval--can be the most ideal place to utilize the expensive toJS calls, as in your example #3. I guess it really depends upon how much one dislikes using Immutable retrieval methods in their "container/smart" components, and/or creating a whole bunch of selectors to retrieve simple JS types from the redux state tree Use Immutable everywhere
To me there's the question of where to actually use the fromJS call, e.g. action creators, in the "container/smart" components dispatch or, in the reducer, e.g. react-boilerplate uses the fromJS call in the reducer.

Categories