I've read a few articles on when to optimize rendering in React, however, I still have some doubts.
const RepairNoticeContainer = () => {
const dispatch = useDispatch();
const history = useHistory();
const { siteType, siteId } = useParams();
const data = useSelector(pageSelectors.getData);
const showRepairNotice = data.grid.cols.lg !== 36;
const handleRepairClick = () => {
dispatch(
pagesActions.copyAndRepairCurrentPage(newPageId => {
history.push(`/editor/${siteType}/${siteId}/pages/${newPageId}`);
})
);
};
return showRepairNotice ? <RepairNotice onRepairClick={handleRepairClick} /> : null;
};
As far as I can understand, it would be beneficial to use useCallbackfor handleRepairClick to avoid rerenders of <RepairNotice/>. But what about showRepairNoticevariable? Should it be wrapped in a useMemo for optimization?
const RepairNotice = ({ onRepairClick }) => {
const translate = useTranslator();
let message = translate("repair_warning");
message = message.charAt(0).toLowerCase() + message.slice(1);
return (
<MessageBox type="warning" icon="information11" className="mb-0 mt-2">
<div className="row">
<div className="col">
<b>{translate("warning")}:</b> {message}
</div>
<div className="col-auto text-right">
<Button color="danger" onClick={onRepairClick} size="small">
{translate("repair_now")}
</Button>
</div>
</div>
</MessageBox>
);
A simillar question for this example. Would it be beneficial to wrap message inside of useMemo?
const Page = ({ status }) => {
const unsavedData = status?.unsavedData ? true : false;
return (
<Fade>
<div className="Page">
<NavConfirmModal active={unsavedData} onSavePage={onSavePage} />
</div>
</Fade>
);
};
Lastly, should useMemo be used unsavedData?
Explanations would be much appreciated.
As far as I can understand, it would be beneficial to use useCallback for handleRepairClick to avoid rerenders of
That's right. while wrapping handleRepairClick you will, simply speak, prevent creating a new instance of this function so it will save RepairNotice nested component from redundant rerenders because it relies on this function in props. Another good case for useMemo is when you're rendering a list of items and each relies on the same handler function declared in their parent.
Very good useCallback explanation here.
But what about showRepairNotice variable? Should it be wrapped in a
useMemo for optimization?
It's just a simple "equation" check which is really cheap from performance side - so there is really no need in useMemo here.
Would it be beneficial to wrap message inside of useMemo?
Yes, it would. Since there are at least 3 actions javascript has to fire upon the message (charAt, toLowerCase, slice) and you don't really want this calculations to fire every time the RepairNotice component gets rerendered.
should useMemo be used unsavedData?
It might be preferable to wrap unsavedData into useMemo if NavConfirmModal will be wrapped in React.Memo or in the case of "heavy calculations". So for the current case - it would not really make a difference. (btw calculating unsavedData could be written just like !!status?.unsavedData to get boolean).
And very good useMemo explanation here.
Related
Let's say I have a React component somewhat like this:
function App() {
const [step, setStep] = useState(0);
const [someValue, setSomeValue] = useState("xyz");
const var1 = "abc";
const var2 = "def";
function StepZero() {
return <div>
<p>{someValue}</p>
<input type="text" id="fname" name="fname" />
<h1>{var1} {var2}</h1>
<Button onClick={() => setSomeValue("123")}>Click</Button>
</div>;
}
function StepOne() {
return <div>
<h1>{someValue}</h1>
<Button onClick={() => setSomeValue("456")}>Click</Button>
<h2>{var1}</h2>
<h3>{var2}</h3>
</div>;
}
return (
<div>
{step === 0 ? (
<StepZero />
) : (
<StepOne />
)}
</div>
);
}
What happens here is, once someValue gets set, the whole StepZero gets re-rendered and the input lost. Really any user interaction gets reset, e.g. an accordion that got opened.
What resolves this is putting StepZero and StepOne directly into the return function, or putting them outside the App component and then passing all the variables in the params like:
{ var1, var2, someValue, setSomeValue }
Is there a better way to do this that I can separate the two steps into components while still being able to access the states and variables/constants, without state changes re-rendering the components every time, or without having to pass all the required variables as parameters?
Note this example app isn't meant to do anything functionally useful
Based on react architecture passing states and variables through props is the best solution.
Now, based on what you requested I have multiple suggestion:
if the constants are resetting, have you tried to save the constants in a ref? (for ex: const var1 = useRef("abc");)
if you don't want to pass data as props but you want them to share the same variables, you can either add Redux (React-redux) or use React Context (How to use React Context)
But if you're project isn't big, i'd suggest you pass them as props, similar to the following:
In the parent App component:
const [step, setStep] = useState(0);
const [someValue, setSomeValue] = useState("xyz");
const var1 = useRef("abc");
const var2 = useRef("def");
And in a separate component
function StepZero({someValue,var1,var2,setSomeValue}) {
return <div>
<p>{someValue}</p>
<input type="text" id="fname" name="fname" />
<h1>{var1.current} {var2.current}</h1>
<Button onClick={() => setSomeValue("123")}>Click</Button>
</div>;
}
First all your child components have to be outside your App function, in order of having their own state.
Secondly you will pass the somevalue state to all your child in a props and lift the state up to your parent with a callback function.
https://reactjs.org/docs/lifting-state-up.html
Something like this (I simplified your code for the example)
function StepZero({val,var1,var2,callback}) {
return <div>
<p>{val}</p>
<input type="text" id="fname" name="fname" />
<h1>{var1} {var2}</h1>
<Button onClick={() => callback("123")}>Click</Button>
</div>;
}
function App() {
const [step, setStep] = useState(0);
const [someValue, setSomeValue] = useState("xyz");
const var1 = "abc";
const var2 = "def";
return (
<div>
<StepZero val={someValue} var1={var1} var2={var2} callback={setSomeValue} />
</div>
);
}
I think you need to know more about how reactjs its work, and base on that you can go...the main idea you need start think about that react is Component-Based, and thats mean "Build encapsulated components that manage their own state"
so, from this point you can know that we have component which its has a control to manage their state, so this will move to next step..
At first level, we have props, state and context, which all of these concepts will help you to pass/share data
1- Props will used to pass data from higher component to nested component, and its immutable
2- State will track your value change and you can updated it to update needed functions...
3- Context which its used to share data between multiple component without passing a props from higher one to lowest one...
After we know about these details, we need to go to step two, which we need to understand Re-render...
The render spitted to initial render which happens when a component first appears on the screen and re-render happens when React needs to update the app with some new data, and usually its happen base on action or interactive action...
Note: react handle the re-render and know which spesfic part is render and handling to re-render it, its virtual dom and can be controlled very well...
Now lets go to your code:
1- You can pass your details as props, and you can split App component to small component:
function StepZero(props) {
return <div>
<p>{props.someValue}</p>
<input type="text" id="fname" name="fname" />
<h1>{var1} {var2}</h1>
<Button onClick={() => props.setSomeValue("123")}>Click</Button>
</div>;
}
function StepOne(props) {
return <div>
<h1>{props.someValue}</h1>
<Button onClick={() => props.setSomeValue("456")}>Click</Button>
<h2>{var1}</h2>
<h3>{var2}</h3>
</div>;
}
function App() {
const [step, setStep] = useState(0);
const [someValue, setSomeValue] = useState("xyz");
const var1 = "abc";
const var2 = "def";
return (
<div>
{step === 0 ? (
<StepZero {youProps}/>
) : (
<StepOne {youProps}/>
)}
</div>
);
}
The second solution is use content React Context
For re-render you need to handling update dependency correctly and if its in loop or list you need to add key
Also, you must know that var1 and var2 will keep re-render since its set direct without state, ref and its put directly in component not a static / const out side the component, so each time you re-render the component its will has a new memory address which its mean a new re-render for any place has lisen to it...
In whichever site I visit to get my doubt clear about state in react I always found this defination in common which is:
"an object of a set of observable properties that control the behavior of the component". And I still don't understand the state in react. Consider an example below
import React,{useState} from 'react';
export const City = ()=>{
const [altitude,setAltitude] = useState("");
const getAltitude=()=>{
navigator.geolocation.watchPosition((position)=>{
const alt = {
lat:position.coords.latitude,
long:position.coords.longitude
}
setAltitude(alt);
console.log(altitude);
})
}
return(
<div id="location">
{getAltitude()}
<h3>This is location</h3>
</div>
)
}
But the above program can also be written without using state as shown below
import React,{useState} from 'react';
export const City = ()=>{
let lat;
let long;
const getAltitude=()=>{
navigator.geolocation.watchPosition((position)=>{
lat = position.coords.latitude;
long = position.coords.longitude;
})
console.log(lat,long);
}
return(
<div id="location">
{getAltitude()}
<h3>This is location</h3>
</div>
)
}
If we can write in this way too then what is the use of state in react.
If I'm wrong I request you to explain me in detail. I'm not able to sleep unless this doubt doesn't get clear.
For the understanding purpose I've created these two snippets, one using state variable and the other using regular js variables.
Using state variable
const { useState } = React;
const Counter = () => {
const [count, setCount] = useState(0);
const onClick = () => {
//Update the state
setCount(c => c + 1);
}
return (
<div>
Count: {count}
<div>
<button onClick={onClick}>Increment</button>
</div>
</div>
)
}
ReactDOM.render(<Counter />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Using regular variable
const { useState } = React;
const Counter = () => {
let count = 0;
const onClick = () => {
//Update the variable
count += 1;
console.log(count);
}
return (
<div>
Count: {count}
<div>
<button onClick={onClick}>Increment</button>
</div>
</div>
)
}
ReactDOM.render(<Counter />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>
In both of the above scenarios we are updating the count on click of the button, but then in scenario 1, the updated value is displayed on the DOM where as in scenario 2, it's not.
So, basically when you want to re-render the component on change of the variable we keep those variables in the state. React will be able to understand the state changes and update the DOM accordingly
As stated correctly in your citation, React maintains a state that is used to to figure out, beside some other features, when to re-render your component. In your examples, it seems like you wanted to add an event listener for watchPosition, and show the calculated values in your City component. If I am correct please consider this example:
import React,{useState} from 'react';
export const City = ()=>{
const [altitude,setAltitude] = useState({});
const calculateAltitude=()=>{
navigator.geolocation.watchPosition((position)=>{
const alt = {
lat:position.coords.latitude,
long:position.coords.longitude
}
setAltitude(alt); // you set the state here
})
}
calculateAltitude(); // This function is called on each render. It's better to put it into a "componentDidMount" equivalent (second example)
return(
<div id="location">
<h3>This is the location</h3>
<div>Lat: {altitude.lat}</div> {/*You use the state here*/}
<div>Lat: {altitude.long}</div>
</div>
)
}
Each time watchPosition is executed, your state altitude is updated and the component will re-render. This means, that the render function is executed and the current state of altitude is used to display the latitude and longitude. In the first example, calculateAltitude() will be executed each time, your component renders. Since that is not best practice, you should put that call into a useEffect hook, with an empty-array dependency. It is an equivalent to the componentDidMount() fucntion for React class components (React.Component). You can find a good explanation here.
So, in order to have a clean code, you should use this component:
import React,{useState, useEffect} from 'react';
export const City = ()=>{
const [altitude,setAltitude] = useState({});
const calculateAltitude=()=>{
navigator.geolocation.watchPosition((position)=>{ // each time this geolocation lib calls your function, your state will be updated.
const alt = {
lat:position.coords.latitude,
long:position.coords.longitude
}
setAltitude(alt); // you set the state here
})
}
useEffect(() =>
{
calculateAltitude() // register your event listener once.
},[]) // on Component mount. Executed once.
return(
<div id="location">
<h3>This is the location</h3>
<div>Lat: {altitude.lat}</div> {/*You use the state here. It is updated each time your geolocation lib calls your listener.*/}
<div>Lat: {altitude.long}</div>
</div>
)
}
I recommend to read carefully about the React states. Here are some good links:
offical doc
article about react states in function
components
One of the features that is at the fundament of React is that it allows you to update your UI, or, in other terms, the HTML output of your app, after a change to a variable. In React, state is a way to declare the variables that, depending on your business logic, can ultimately update the UI. React does this by keeping track of the state and rerendering parts of the HTML that need the update.
In your example, you made altitude part of your state, but your logic does not update the UI anywhere—it just determines a geolocation on first load. If this is what you want, that's fine, you won't need state for that. If, however, you want to make updates to your HTML, e.g. if you'd like to show the realtime location of a user on a map, you could make use of React's state: you write location updates to the state, and will need some custom logic that handles what happens if the altitude value has changed. You could write this custom logic as a side effect.
state variables will be accessible into jsx ( i mean in rendered part of the component), so in your example, altitude will be accessible in the html part, but if you didn't assign it to state variable wont be able to access it
return(
<div id="location">
<h3>This is location {altitude.alt}</h3>
</div>
)
So I became tired of using a bunch of memo, useMemo, and useCallbacks to keep my layered app responsive. Instead I built a react hook called useStateChange (I don't often need immediate updates provided by onChange).
function useStateChange(valuesInit) {
const [values, valuesSet] = useState(valuesInit);
useEffect(() => valuesSet(valuesInit), [valuesInit]);
const onChange = useCallback(({ target: { value } }) => valuesSet(value), []);
return [onChange, values, valuesSet];
}
function TestInput({ value0, onBlur }) {
console.log("Test ran");
const [onChange, value1] = useStateChange(value0);
return (
<>
<h4>
Value1:{" "}
<input type="text" value={value1} onChange={onChange} onBlur={onBlur} />
</h4>
<h5>Value1: {value1}</h5>
</>
);
}
Working example can be found at CodeSandbox.
Since this function will be used with nearly every input, is there any way to further improve the performance?
I know people will nag about not over optimizing but this will become a critical component of my app and its better if its functioning at its best. If I had optimized with my useStateChange function, I wouldn't had my current performance problems...
React Hooks documentation says to not call Hooks inside loops, conditions, or nested functions.
I understood that the order of execution was important so React can know which state corresponds to which useState call. Given that, it's obvious that a hook cannot be called inside a condition.
But I don't see what is the problem if we call useState inside a loop where the number of iterations doen't change over the time. Here is an example :
const App = () => {
const inputs = [];
for(let i = 0; i < 10; i++) {
inputs[i] = useState('name' + i);
}
return inputs.map(([value, setValue], index) => (
<div key={index}>
<input value={value} onChange={e => setValue(e.target.value)} />
</div>
));
}
export default App;
Is there a problem with this code above ? And what is the problem of calling useState inside a nested function, if this function is called on every render ?
The reference states the actual cause,
By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
and provides the example that shows why this is important.
Loops, conditions and nested functions are common places where the order in which hooks are executed may be disturbed. If a developer is sure that a loop, etc. is justified and guarantees the order then there's no problem.
In fact, a loop would be considered valid custom hook if it was extracted to a function, a linter rule can be disabled where needed (a demo):
// eslint-disable-next-line react-hooks/rules-of-hooks
const useInputs = n => [...Array(n)].map((_, i) => useState('name' + i));
The example above won't cause problems but a loop isn't necessarily justified; it can be a single array state:
const App = () => {
const [inputs, setInputs] = useState(Array(10).fill(''));
const setInput = (i, v) => {
setInputs(Object.assign([...inputs], { [i]: v }));
};
return inputs.map((v, i) => (
<div key={i}>
<input value={v} onChange={e => setInput(i, e.target.value)} />
</div>
));
}
I'm trying to convert this cool <canvas> animation I found here into a React reusable component. It looks like this component would require one parent component for the canvas, and many children components for the function Ball().
It would probably be better for performance reasons to make the Balls into stateless components as there will be many of them. I'm not as familiar with making stateless components and wondered where I should define the this.update() and this.draw functions defined in function Ball().
Do functions for stateless components go inside the component or outside? In other words, which of the following is better?
1:
const Ball = (props) => {
const update = () => {
...
}
const draw = () => {
...
}
return (
...
);
}
2:
function update() {
...
}
function draw() {
...
}
const Ball = (props) => {
return (
...
);
}
What are the pros and cons of each and is one of them better for specific use cases such as mine?
The first thing to note is that stateless functional components cannot have methods: You shouldn't count on calling update or draw on a rendered Ball if it is a stateless functional component.
In most cases you should declare the functions outside the component function so you declare them only once and always reuse the same reference. When you declare the function inside, every time the component is rendered the function will be defined again.
There are cases in which you will need to define a function inside the component to, for example, assign it as an event handler that behaves differently based on the properties of the component. But still you could define the function outside Ball and bind it with the properties, making the code much cleaner and making the update or draw functions reusable:
// you can use update somewhere else
const update = (propX, a, b) => { ... };
const Ball = props => (
<Something onClick={update.bind(null, props.x)} />
);
If you're using hooks, you can use useCallback to ensure the function is only redefined when any of its dependencies change (props.x in this case):
const Ball = props => {
const onClick = useCallback((a, b) => {
// do something with a, b and props.x
}, [props.x]);
return (
<Something onClick={onClick} />
);
}
This is the wrong way:
const Ball = props => {
function update(a, b) {
// props.x is visible here
}
return (
<Something onClick={update} />
);
}
When using useCallback, defining the update function in the useCallback hook itself or outside the component becomes a design decision more than anything: You should take into account if you're going to reuse update and/or if you need to access the scope of the component's closure to, for example, read/write to the state. Personally I choose to define it inside the component by default and make it reusable only if the need arises, to prevent over-engineering from the start. On top of that, reusing application logic is better done with more specific hooks, leaving components for presentational purposes. Defining the function outside the component while using hooks really depends on the grade of decoupling from React you want for your application logic.
Another common discussion about useCallback is whether to always use it for every function or not. That is, treat is as opt-in or always recommendable. I would argue to always use useCallback: I've seen many bugs caused by not wrapping a function in useCallback and not a single scenario where doing so affects the performance or logic in any way. In most cases, you want to keep a reference while the dependencies don't change, so you can use the function itself as a dependency for other effects, memos or callback. In many cases the callback will be passed as a prop to other elements, and if you memoized it with useCallback you won't change the props (thus re-render) other components independently of how cheap or costly that would be. I've seen many thousands of functions declared in components and not a single case in which using useCallback would have any down side. On the other hand most functions not memoized with useCallback would eventually be changed to do so, causing serious bugs or performance issues if the developer doesn't recognize the implications of not doing so. Technically there is a performance hit by using useCallback, as you would be creating and additional function but it is negligible compared to the re-declaration of the function that always has to happen either you use useCallback or not and the overall footprint of React and JavaScript. So, if you are really concerned about the performance impact of useCallback versus not using it, you should be questioning yourself if React is the right tool for the job.
You can place functions inside stateless functional components:
function Action() {
function handlePick(){
alert("test");
}
return (
<div>
<input type="button" onClick={handlePick} value="What you want to do ?" />
</div>
)
}
But it's not a good practice as the function handlePick() will be defined every time the component is rendered.
It would be better to define the function outside the component:
function handlePick(){
alert("test");
}
function Action() {
return (
<div>
<input type="button" onClick={handlePick} value="What you want to do ?" />
</div>
)
}
If you want to use props or state of component in function, that should be defined in component with useCallback.
function Component(props){
const onClick=useCallback(()=>{
// Do some things with props or state
},[])
return <Something {...{onClick}} />
}
On the other hand, if you don't want to use props or state in function, define that outside of component.
const computeSomethings=()=>{
// Do some things with params or side effects
}
function Component(props){
return <Something onClick={computeSomethings} />
}
For HTML tags you don't need useCallback because that will handle in react side and will not be assigned to HTML
function Component(props){
const onClick=()=>{
// Do some things with props or state
}
return <div {...{onClick}} />
}
Edit: Functions in hooks
For the use function in hooks for example useEffect, my suggestion is defining function inside useEffect, if you're worried about DRY, make your function pure call it in hook and give your params to it.
What about hooks deps? You should/could add all of your params to hooks deps, but useEffect just needs deps which should affect for them changes.
We can use the React hook useCallback as below in a functional component:
const home = (props) => {
const { small, img } = props
const [currentInd, setCurrentInd] = useState(0);
const imgArrayLength = img.length - 1;
useEffect(() => {
let id = setInterval(() => {
if (currentInd < imgArrayLength) {
setCurrentInd(currentInd => currentInd + 1)
}
else {
setCurrentInd(0)
}
}, 5000);
return () => clearInterval(id);
}, [currentInd]);
const onLeftClickHandler = useCallback(
() => {
if (currentInd === 0) {
}
else {
setCurrentInd(currentInd => currentInd - 1)
}
},
[currentInd],
);
const onRightClickHandler = useCallback(
() => {
if (currentInd < imgArrayLength) {
setCurrentInd(currentInd => currentInd + 1)
}
else {
}
},
[currentInd],
);
return (
<Wrapper img={img[currentInd]}>
<LeftSliderArrow className={currentInd > 0 ? "red" : 'no-red'} onClick={onLeftClickHandler}>
<img src={Icon_dir + "chevron_left_light.png"}></img>
</LeftSliderArrow>
<RightSliderArrow className={currentInd < imgArrayLength ? "red" : 'no-red'} onClick={onRightClickHandler}>
<img src={Icon_dir + "chevron_right_light.png"}></img>
</RightSliderArrow>
</Wrapper>);
}
export default home;
I'm getting 'img' from it's parent and that is an array.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
const a = () => {
setCount(count + 1);
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={a}>Click me</button>
</div>
);
}
export default Example;