Manage checkbox state in an infinite scrolling table using React - javascript

Please see this codesandbox.
This codesandbox simulates a problem I am encountering in my production application.
I have an infinite scrolling table that includes checkboxes, and I need to manage the every-growing list of checkboxes and their state (checked vs non-checked). The checkboxes are rendered via vanilla functions (see getCheckbox) that render the React components. However, my checkboxes do not seem to be maintaining the parent state (called state in the code) and clicking a checkbox does not work. What do I need to do to make sure that clicking a checkbox updates state and that all of the checkboxes listen to state? Thanks! Code is also below:
index.js:
import ReactDOM from "react-dom";
import "#elastic/eui/dist/eui_theme_amsterdam_light.css";
import React, { useState, useEffect } from "react";
import { EuiCheckbox, htmlIdGenerator } from "#elastic/eui";
import { arrayRange, getState } from "./utils";
const Checkbox = ({ id, isChecked, onClick }) => (
<div style={{ margin: "1rem" }}>
<EuiCheckbox
id={htmlIdGenerator()()}
label={isChecked ? `${id} - On` : `${id} - Off`}
checked={isChecked}
onChange={() => onClick()}
/>
</div>
);
const getCheckbox = (props) => <Checkbox {...props} />;
const App = () => {
const [state, setState] = useState(getState(0, 1));
const [checkboxes, setCheckboxes] = useState([]);
const [addMoreCheckboxes, setAddMoreCheckboxes] = useState(true);
useEffect(() => {
if (addMoreCheckboxes) {
setAddMoreCheckboxes(false);
setTimeout(() => {
setState((prevState) => ({
...prevState,
...getState(checkboxes.length, checkboxes.length + 1)
}));
const finalCheckboxes = [...checkboxes].concat(
arrayRange(checkboxes.length, checkboxes.length + 1).map((id) =>
getCheckbox({
id,
isChecked: state[id],
onClick: () => handleClick(id)
})
)
);
setCheckboxes(finalCheckboxes);
setAddMoreCheckboxes(true);
}, 3000);
}
}, [addMoreCheckboxes]);
const handleClick = (id) =>
setState((prevState) => ({
...prevState,
[id]: !prevState[id]
}));
return <div style={{ margin: "5rem" }}>{checkboxes}</div>;
};
ReactDOM.render(<App />, document.getElementById("root"));
utils.js:
export const arrayRange = (start, end) =>
Array(end - start + 1)
.fill(null)
.map((_, index) => start + index);
export const getState = (start, end) => {
const state = {};
arrayRange(start, end).forEach((index) => {
state[index] = false;
});
return state;
};

There is one main reason your checkboxes are not updating.
It's your checkboxes state variable
This variable does not contain the data, but rather contains the processed React JSX elements themselves.
Not a wrong practice, but is uncommon. Kind of makes it easy to lose track of where data is actually stored, etc. I'd recommend using useMemo for UI-related memoization instead.
Related to previous point. Observe how in useEffect, when you're trying to append new data to the checkboxes variable, you're using the spread operator from the previous checkboxes value
Since the checkboxes value are simply processed JSX, they aren't re-rendered or re-processed (they are simply "there", like drawn pictures! No relations to the state at all!)
So basically, this operation is just adding new "drawings" of unchecked checkboxes to a previous list of drawn JSXes. So you just get a longer list of immutable, pre-rendered JSX checkboxes stuck in the unchecked state!
So.. to fix this I'd recommend that you separate data state from UI drawings. And maybe use useMemo to help.
I minimally modified your code, and it's located here (https://codesandbox.io/s/cranky-firefly-9ibgr). This should behave like you expect.
Here's the same exact modified code as in the sandbox for convenience.
import ReactDOM from "react-dom";
import "#elastic/eui/dist/eui_theme_amsterdam_light.css";
import React, { useState, useEffect, useMemo } from "react";
import { EuiCheckbox, htmlIdGenerator } from "#elastic/eui";
import { arrayRange, getState } from "./utils";
const Checkbox = ({ id, isChecked, onClick }) => (
<div style={{ margin: "1rem" }}>
<EuiCheckbox
id={htmlIdGenerator()()}
label={isChecked ? `${id} - On` : `${id} - Off`}
checked={isChecked}
onChange={() => onClick()}
/>
</div>
);
const getCheckbox = (props, key) => <Checkbox {...props} key={key}/>;
const App = () => {
// The checkbox check/uncheck state variable
const [state, setState] = useState(getState(0, 1));
// Checkboxes now just contains the `id` of each checkbox (purely data)
const [checkboxes, setCheckboxes] = useState([]);
const [addMoreCheckboxes, setAddMoreCheckboxes] = useState(true);
useEffect(() => {
if (addMoreCheckboxes) {
setAddMoreCheckboxes(false);
setTimeout(() => {
setState((prevState) => ({
...prevState,
...getState(checkboxes.length, checkboxes.length + 1)
}));
// Add new ids to the list
const finalCheckboxes = [...checkboxes].concat(
arrayRange(checkboxes.length, checkboxes.length + 1)
);
setCheckboxes(finalCheckboxes);
setAddMoreCheckboxes(true);
}, 3000);
}
}, [addMoreCheckboxes]);
const handleClick = (id) => {
setState((prevState) => ({
...prevState,
[id]: !prevState[id]
}));
};
// use useMemo to check for rerenders. (kind of like, data-driven UI)
const renderedCheckboxes = useMemo(() => {
return checkboxes.map((id) => {
// I'm adding a second argument to `getCheckbox` for its key
// This is because `React` lists (arrays of JSXs) need keys on each JSX components
// You could also just skip the function calling altogether
// and create the <Checkbox .../> here. There's little performance penalty
return getCheckbox({
id,
isChecked: state[id],
onClick: () => handleClick(id)
}, id)
});
}, [checkboxes, state]);
return <div style={{ margin: "5rem" }}>{renderedCheckboxes}</div>;
};
ReactDOM.render(<App />, document.getElementById("root"));
P.S. I agree with Oliver's comment that using useEffect with another toggle (addMoreCheckboxes) is quite unorthodox. I would suggest refactoring it to setInterval (or maybe a setTimeout with a boolean condition in a useEffect, in case you want more control).

The main problem here is that checkboxes is not directly dependent on state (the only time a checkbox is related to state is when a it is initialised with isChecked: state[id]).
This means that even though your state variable updates correctly when a checkbox is clicked, this will not be reflected on the checkbox itself.
The quickest fix here would be to amend the JSX returned by your component so as to directly infer the isChecked property for the checkboxes from the current state:
const App = () => {
// [...]
return <div style={{ margin: "5rem" }}>
{Object.keys(state).map((id) => getCheckbox({
id,
isChecked: state[id],
onClick: () => handleClick(id),
}))
}
</div>;
};
You may however notice now that your checkboxes state variable is becoming rather unnecessary (state being sufficient and holding all the necessary information for rendering all the right checkboxes). So you could consider rewriting your logic without the redundant checkboxes state variable.
As a side note, you are using useEffect() in combination with the addMoreCheckboxes state variable as a kind of timer here. You could simplify that portion of the code through the use of the probably more appropriate setInterval()

Related

eslint wants me to add a dependency to useEffect but doing so causes an infinite loop

I appreciate this is a common issue on here but I'm struggling to think of a workaround for my particular situation. My code works as intended but I'm getting an eslint warning about the missing dependency in useEffect. The missing dependency is a function which sends the state to the parent, but if I add it as a dependency it causes an infinite loop.
Here's my child component CheckboxGroup.js:
The itemId and checkedState get lifted from its child (CheckboxItem.js) and the selectedItemIds state gets updated. I've then used useEffect because selectedItemIds needs to get lifted to its parent (App.js) immediately. As you can see, it's missing onSelectHandler in its list of dependencies.
const CheckboxGroup = (props) => {
const categoryName = props.items[0].category;
const [selectedItemIds, setSelectedItemIds] = useState([
...props.defaultCheckboxIds,
]);
const clickHandler = (itemId, checkedState) => {
checkedState
? setSelectedItemIds((prev) => [...prev, itemId])
: setSelectedItemIds((prev) => prev.filter((c) => c !== itemId));
};
//destructure prop
const onSelectHandler = props.onSelectHandler;
useEffect(() => {
onSelectHandler(categoryName, selectedItemIds)
}, [categoryName, selectedItemIds]);
return (
<ul className="card__inner">
{props.items.map((item) => {
return (
<CheckboxItem
isChecked={selectedItemIds.includes(item.id)}
id={item.id}
name={item.name}
price={item.price}
category={item.category}
key={item.id}
onClick={clickHandler}
/>
);
})}
</ul>
);
};
Here's the function in App.js which receives the data and then updates the selections state.
const [selections, setSelections] = useState({
chairs: 2,
tables: 8,
"large tables": [10, 12]
});
const selectionHandler = (selectedCategoryName, selectedItemIds) => {
setSelections((prev) => ({
...prev,
[selectedCategoryName]: selectedItemIds,
}));
};
So I'm wondering if there's a way I can either include the dependency in useEffect without it triggering an infinite loop or there's an alternative way of lifting the state, perhaps without useEffect?
Any help appreciated, thanks.
You can use useCallback from React to memoize selectionHandler. This way you can safely add it in the dependency array:
import { useCallback } from "react";
const selectionHandler = useCallback((selectedCategoryName, selectedItemIds) => {
setSelections((prev) => ({
...prev,
[selectedCategoryName]: selectedItemIds,
}));
}, []);

Prevent checkboxes from re-rendering in React

I'm trying to render multiple checkboxes based on dynamic return data and have their checked status stored in a local state.
However the performance starts to degrade when higher number of checkboxes are generated. I noticed the issue is due to the constant re-rendering of ALL the checkboxes whenever any one of them is checked (checkbox states are all stored in the same object with different keys)
Here is my sample code and a codesandbox link to see the actual performance issue (notice the delay when a checkbox is selected)
export default function App() {
const [checkboxResponse, setCheckboxResponse] = useState([]);
const [checkboxList, setCheckboxList] = useState();
const [checkboxStates, setCheckboxStates] = useState({});
useEffect(() => {
//Generate dummy data
const dummyData = [];
for (let i = 0; i < 1000; i++) {
dummyData.push(i.toString());
}
//Set dummyData as checkbox dynamic data
setCheckboxResponse(dummyData);
}, []);
useEffect(() => {
//When checkbox is clicked, add to local checkbox states object
const checkboxChange = key => event => {
setCheckboxStates({ ...checkboxStates, [key]: event.target.checked });
};
//Check if data is available
if (checkboxResponse) {
const checkboxes = checkboxResponse.map(key => {
const value = checkboxStates[key] ? checkboxStates[key] : false;
//Render checkbox
return (
<FormControlLabel
key={key}
checked={value}
control={
<Checkbox
size="small"
value={key}
onChange={checkboxChange(key)}
/>
}
label={key}
/>
);
});
setCheckboxList(checkboxes);
}
}, [checkboxResponse, checkboxStates]);
return (
<div className="App">
{checkboxList}
</div>
);
}
CodeSandbox
It seems that whenever checkboxStates is changed, the useEffect hook is re-run, triggering a re-render of all the checkboxes again.
Is it possible to prevent React from re-rendering all the checkboxes again whenever the state is changed? Or do we have to create a separate state for every single checkbox dynamically?
Any help would be greatly appreciated.
You can use React.memo to prevent re-render of unchanged check-boxes. Like this:
import React, { useState, useEffect } from "react";
import { Checkbox, FormControlLabel } from "#material-ui/core";
import "./styles.css";
export default function App() {
const [checkboxResponse, setCheckboxResponse] = useState([]);
const [checkboxStates, setCheckboxStates] = useState({});
//When checkbox is clicked, add to local checkbox states object
const checkboxChange = key => event => {
setCheckboxStates({ ...checkboxStates, [key]: event.target.checked });
};
useEffect(() => {
//Generate dummy data
const dummyData = [];
for (let i = 0; i < 1000; i++) {
dummyData.push(i.toString());
}
//Set dummyData as checkbox dynamic data
setCheckboxResponse(dummyData);
}, []);
return (
<div className="App">
{checkboxResponse.map(key => {
const value = checkboxStates[key] ? checkboxStates[key] : false;
//Render checkbox
return (
<FormControlLabel
key={key}
checked={value}
control={<MemoCheckbox key={key} checkboxChange={checkboxChange} />}
label={key}
/>
);
})}
</div>
);
}
const CustomCheckbox = ({ key, checkboxChange }) => (
<Checkbox size="small" value={key} onChange={checkboxChange(key)} />
);
const MemoCheckbox = React.memo(
CustomCheckbox,
(prev, next) => prev.key === next.key
);
However, it might still be not fast enough as when you click the checkbox it still loops trough .map and creates elements.
Here is docs reference for Memo

Usage of useCallback and setting new object state using previous state as argument

Consider this basic form fields component with a custom form hook to handle input changes:
import React, { useState, useCallback } from 'react';
const useFormInputs = (initialState = {})=> {
const [values, setValues] = useState(initialState);
const handleChange = useCallback(({ target: { name, value } }) => {
setValues(prev => ({ ...prev, [name]: value }));
}, []);
const resetFields = useCallback(() =>
setValues(initialState), [initialState]);
return [values, handleChange, resetFields];
};
const formFields = [
{ name: 'text', placeholder: 'Enter text...', type: 'text', text: 'Text' },
{ name: 'amount', placeholder: 'Enter Amount...', type: 'number',
text: 'Amount (negative - expense, positive - income)' }
];
export const AddTransaction = () => {
const [values, handleChange, resetFields] = useFormInputs({
text: '', amount: ''
});
return <>
<h3>Add new transaction</h3>
<form>
{formFields.map(({ text, name, ...attributes }) => {
const inputProps = { ...attributes, name };
return <div key={name} className="form-control">
<label htmlFor={name}>{text}</label>
<input {...inputProps} value={values[name]}
onChange={handleChange} />
</div>;
})}
<button className="btn">Add transaction</button>
</form>
<button className="btn" onClick={resetFields}>Reset fields</button>
</>;
};
Is there really any reason / advantage for me to use useCallback to cache the function in my custom hook? I read the docs, but I just coudln't grasp the idea behind this usage of useCallback. How exactly it memoizes the function between renders? How exactly does ti work, and should I use it?
Inside the same custom hook, you can see the new values state being updated by spreading the previous state and creating a new object like so: setValues(prev => ({ ...prev, [name]: value }));
Would there be any difference if I did this instead? setValues({ ...prev, [name]: value })
as far as I can tell, doesn't look like it has any difference right? I am simply accessing the state directly.. Am I wrong?
Your first question:
In your case it doesn't matter because everything is rendered in the same component. If you have a list of things that get an event handler then useCallback can save you some renders.
In the example below the first 2 items are rendered with an onClick that is re created every time App re renders. This will not only cause the Items to re render it will also cause virtual DOM compare to fail and React will re create the Itms in the DOM (expensive operation).
The last 2 items get an onClick that is created when App mounts and not re created when App re renders so they will never re render.
const { useState, useCallback, useRef, memo } = React;
const Item = memo(function Item({ onClick, id }) {
const rendered = useRef(0);
rendered.current++;
return (
<button _id={id} onClick={onClick}>
{id} : rendered {rendered.current} times
</button>
);
});
const App = () => {
const [message, setMessage] = useState('');
const onClick = (e) =>
setMessage(
'last clicked' + e.target.getAttribute('_id')
);
const memOnClick = useCallback(onClick, []);
return (
<div>
<h3>{message}</h3>
{[1, 2].map((id) => (
<Item key={id} id={id} onClick={onClick} />
))}
{[1, 2].map((id) => (
<Item key={id} id={id} onClick={memOnClick} />
))}
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Another example is when you want to call a function in an effect that also needs to be called outside of the effect so you can't put the function inside the effect. You only want to run the effect when a certain value changes so you can do something like this.
//fetchById is (re) created when ID changes
const fetchById = useCallback(
() => console.log('id is', ID),
[ID]
);
//effect is run when fetchById changes so basically
// when ID changes
useEffect(() => fetchById(), [fetchById]);
Your second question:
The setValues({ ...prev, [name]: value }) will give you an error because you never defined pref but if you meant: setValues({ ...values, [name]: value }) and wrap the handler in a useCallback then now your callback has a dependency on values and will be needlessly be re created whenever values change.
If you don't provide the dependency then the linter will warn you and you end up with a stale closure. Here is an example of the stale closure as counter.count will never go up because you never re create onClick after the first render thus the counter closure will always be {count:1}.
const { useState, useCallback, useRef } = React;
const App = () => {
const [counts, setCounts] = useState({ count: 1 });
const rendered = useRef(0);
rendered.current++;
const onClick = useCallback(
//this function is never re created so counts.count is always 1
// every time it'll do setCount(1+1) so after the first
// click this "stops working"
() => setCounts({ count: counts.count + 1 }),
[] //linter warns of missing dependency count
);
return (
<button onClick={onClick}>
count: {counts.count} rendered:{rendered.current}
</button>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

React Hooks multiple alerts with individual countdowns

I've been trying to build an React app with multiple alerts that disappear after a set amount of time. Sample: https://codesandbox.io/s/multiple-alert-countdown-294lc
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function TimeoutAlert({ id, message, deleteAlert }) {
const onClick = () => deleteAlert(id);
useEffect(() => {
const timer = setTimeout(onClick, 2000);
return () => clearTimeout(timer);
});
return (
<p>
<button onClick={onClick}>
{message} {id}
</button>
</p>
);
}
let _ID = 0;
function App() {
const [alerts, setAlerts] = useState([]);
const addAlert = message => setAlerts([...alerts, { id: _ID++, message }]);
const deleteAlert = id => setAlerts(alerts.filter(m => m.id !== id));
console.log({ alerts });
return (
<div className="App">
<button onClick={() => addAlert("test ")}>Add Alertz</button>
<br />
{alerts.map(m => (
<TimeoutAlert key={m.id} {...m} deleteAlert={deleteAlert} />
))}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
The problem is if I create multiple alerts, it disappears in the incorrect order. For example, test 0, test 1, test 2 should disappear starting with test 0, test 1, etc but instead test 1 disappears first and test 0 disappears last.
I keep seeing references to useRefs but my implementations don't resolve this bug.
With #ehab's input, I believe I was able to head down the right direction. I received further warnings in my code about adding dependencies but the additional dependencies would cause my code to act buggy. Eventually I figured out how to use refs. I converted it into a custom hook.
function useTimeout(callback, ms) {
const savedCallBack = useRef();
// Remember the latest callback
useEffect(() => {
savedCallBack.current = callback;
}, [callback]);
// Set up timeout
useEffect(() => {
if (ms !== 0) {
const timer = setTimeout(savedCallBack.current, ms);
return () => clearTimeout(timer);
}
}, [ms]);
}
You have two things wrong with your code,
1) the way you use effect means that this function will get called each time the component is rendered, however obviously depending on your use case, you want this function to be called once, so change it to
useEffect(() => {
const timer = setTimeout(onClick, 2000);
return () => clearTimeout(timer);
}, []);
adding the empty array as a second parameter, means that your effect does not depend on any parameter, and so it should only be called once.
Your delete alert depends on the value that was captured when the function was created, this is problematic since at that time, you don't have all the alerts in the array, change it to
const deleteAlert = id => setAlerts(alerts => alerts.filter(m => m.id !== id));
here is your sample working after i forked it
https://codesandbox.io/s/multiple-alert-countdown-02c2h
well your problem is you remount on every re-render, so basically u reset your timers for all components at time of rendering.
just to make it clear try adding {Date.now()} inside your Alert components
<button onClick={onClick}>
{message} {id} {Date.now()}
</button>
you will notice the reset everytime
so to achieve this in functional components you need to use React.memo
example to make your code work i would do:
const TimeoutAlert = React.memo( ({ id, message, deleteAlert }) => {
const onClick = () => deleteAlert(id);
useEffect(() => {
const timer = setTimeout(onClick, 2000);
return () => clearTimeout(timer);
});
return (
<p>
<button onClick={onClick}>
{message} {id}
</button>
</p>
);
},(oldProps, newProps)=>oldProps.id === newProps.id) // memoization condition
2nd fix your useEffect to not run cleanup function on every render
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
finally something that is about taste, but really do you need to destruct the {...m} object ? i would pass it as a proper prop to avoid creating new object every time !
Both answers kind of miss a few points with the question, so after a little while of frustration figuring this out, this is the approach I came to:
Have a hook that manages an array of "alerts"
Each "Alert" component manages its own destruction
However, because the functions change with every render, timers will get reset each prop change, which is undesirable to say the least.
It also adds another lay of complexity if you're trying to respect eslint exhaustive deps rule, which you should because otherwise you'll have issues with state responsiveness. Other piece of advice, if you are going down the route of using "useCallback", you are looking in the wrong place.
In my case I'm using "Overlays" that time out, but you can imagine them as alerts etc.
Typescript:
// useOverlayManager.tsx
export default () => {
const [overlays, setOverlays] = useState<IOverlay[]>([]);
const addOverlay = (overlay: IOverlay) => setOverlays([...overlays, overlay]);
const deleteOverlay = (id: number) =>
setOverlays(overlays.filter((m) => m.id !== id));
return { overlays, addOverlay, deleteOverlay };
};
// OverlayIItem.tsx
interface IOverlayItem {
overlay: IOverlay;
deleteOverlay(id: number): void;
}
export default (props: IOverlayItem) => {
const { deleteOverlay, overlay } = props;
const { id } = overlay;
const [alive, setAlive] = useState(true);
useEffect(() => {
const timer = setTimeout(() => setAlive(false), 2000);
return () => {
clearTimeout(timer);
};
}, []);
useEffect(() => {
if (!alive) {
deleteOverlay(id);
}
}, [alive, deleteOverlay, id]);
return <Text>{id}</Text>;
};
Then where the components are rendered:
const { addOverlay, deleteOverlay, overlays } = useOverlayManger();
const [overlayInd, setOverlayInd] = useState(0);
const addOverlayTest = () => {
addOverlay({ id: overlayInd});
setOverlayInd(overlayInd + 1);
};
return {overlays.map((overlay) => (
<OverlayItem
deleteOverlay={deleteOverlay}
overlay={overlay}
key={overlay.id}
/>
))};
Basically: Each "overlay" has a unique ID. Each "overlay" component manages its own destruction, the overlay communicates back to the overlayManger via prop function, and then eslint exhaustive-deps is kept happy by setting an "alive" state property in the overlay component that, when changed to false, will call for its own destruction.

useState always is default value in itself

I'm using useState to manage the state, it's working fine. But when i return state inside itseft, it always value of initial
import react, {useState} from 'react'
const MyComponent = () => {
const [myState, setMyState] = useState({
value: 'initial value',
setValue: (newValue) => {
setMyState({...myState, value: newValue})
console.log(myState.value) //<--always is 'initial value'
}
})
return(
<>
<p>{myState.value}</p> //<-- it's working fine
<input value={myState.value} onChange={(e) => myState.setValue(e.target.value)} /> //<--working fine too
</>
)
}
I expect the console.log is value of input, but the actual output always is initial value
const [myState, setMyState] = useState({
value: 'initial value',
setValue: (newValue) => {
setMyState({...myState, value: newValue})
console.log(myState.value) //<--always is 'initial value'
}
})
The first time your component function is run, the setValue function captures the initial value of myState. The second time it is run, you make a copy of the setValue function—but this is the function that has has captured the initial value of myState. It never updates.
Since the function never changes, you should not put it in useState() in the first place. You can define the function separately.
const [myState, setMyState] = useState({ value: 'initial value' })
const setValue = (newValue) => {
setMyState({ ...myState, value: newValue })
}
Now, a new setValue copy is created every time the component function is run. When capturing variables, you can use useCallback() for optimization; if the values didn't change, React will reuse old copies of the function.
const [myState, setMyState] = useState({ value: 'initial value' })
const setValue = useCallback((newValue) => {
setMyState({ ...myState, value: newValue })
}, [myState]) // ← this bit ensures that the value is always up to date inside the callback
As mentioned by Shubham Khatri, there is an even faster and better approach in this situation: using the functional form of setState.
const [myState, setMyState] = useState({ value: 'initial value' })
const setValue = useCallback((newValue) => {
setMyState((prev) => ({ ...prev, value: newValue }))
}, []) // ← now we use an empty array, so React will never update this callback
Any of these three methods are fine to use, though; they will all work and perform good enough for most use cases.
Per comments, you're attempting to create an object that is passed down via context. A way to do this is by creating the context object in a separate step, similarly to how we created the callback function. This time, we use useMemo, which is similar to useCallback but works for any type of object.
// Per T.J. Crowder's answer, you can use separate `useState` calls if you need multiple values.
const [myState, setMyState] = useState('initial value')
const ctx = useMemo(() => ({
value: myState,
setValue: (newValue) => {
setMyState(newValue)
}
}), [myState])
return (
<Provider value={ctx}>
{children}
</Provider>
)
goto-bus-stop's answer explains why you're getting the problem you're getting. But there's another thing to address here:
From the code you've provided, it looks like you're using an object as your state value. In particular, this line:
setMyState({...myState, value: newValue})
..suggests you intend myState to have multiple things in it, with value just being one of them.
That's not how you do it with hooks. It's fine to have an object as a state value, but generally you do that when you're going to update (that is, replace) the entire object when the state changes. If you're updating individual parts of the state (as suggested by the above), you use individual useState calls instead of an object. See comments:
const {useState} = React;
const MyComponent = () => {
// Separate `useState` calls for each state item
const [value, setValue] = useState('initial value');
const [anotherValue, setAnotherValue] = useState('another value');
// No need to create your own update function, that's what `setValue` and
// `setAnotherValue` are, just use them:
return(
<React.Fragment>
<p>{value}</p>
<input value={value} onChange={(e) => setValue(e.target.value)} />
<p>{anotherValue}</p>
<input value={anotherValue} onChange={(e) => setAnotherValue(e.target.value)} />
</React.Fragment>
);
}
ReactDOM.render(<MyComponent />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
This separation is particularly useful if you have any side effects of state changes, because you can specify what state triggers the side effect. For instance, here's the component above which triggers a console.log when value changes but not when anotherValue changes, and another effect that occurs when either of them changes:
const {useState, useEffect} = React;
const MyComponent = () => {
// Separate `useState` calls for each state item
const [value, setValue] = useState('initial value');
const [anotherValue, setAnotherValue] = useState('another value');
// A counter for all changes; we use -1 because
// our effect runs on initial mount
const [changes, setChanges] = useState(-1);
// No need to create your own update function, that's what `setValue` and
// `setAnotherValue` are, just use them:
// A side-effect for when `value` changes:
useEffect(() => {
console.log(`value changed to ${value}`);
}, [value]); // <=== Notice that we declare what triggers this effect
// A side-effect for when *either* `value` or `anotherValue` changes:
useEffect(() => {
setChanges(changes + 1);
}, [value, anotherValue]);
return(
<React.Fragment>
<p>Total changes: {changes}</p>
<p>{value}</p>
<input value={value} onChange={(e) => setValue(e.target.value)} />
<p>{anotherValue}</p>
<input value={anotherValue} onChange={(e) => setAnotherValue(e.target.value)} />
</React.Fragment>
);
}
ReactDOM.render(<MyComponent />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
A better way to do this will be
import react, {useState} from 'react'
const MyComponent = () => {
const [ value, setValue ] = useState('initial value');
const handleChange = (e) => {
setValue(e.target.value);
}
return(
<>
<p>{myState}</p>
<input value={myState.value} onChange={handleChange} />
</>
)
}
Firstly the function inside the useState argument isn't aware of the update since its only called once and has the value from its closure. Secondly the way you are using useState is not correct, you must instead only have the value in useState and have the handlers outside
Also you must use callback pattern
import react, {useState} from 'react'
const MyComponent = () => {
const [myState, setMyState] = useState('initial value');
const setValue = (newValue) => {
setMyState(newValue)
}
console.log(myState);
return(
<>
<p>{myState}</p>
<input value={myState} onChange={(e) => setValue(e.target.value)} />
</>
)
}
Also state update is asynchronous so the update is not reflected immediately instead after the next render

Categories

Resources