score:2
Why does it currently behave as it does?
<Rand />
doesn't call your component function. It just calls React.createElement
to create the React element (not an instance of it). Your component function is used to render an element instance, if and when you use it. In your "working" example you're doing:
<>{Math.random()}</>
...which calls Math.random
and uses its result as text (not a component) within the fragment.
But your "not working" example just does:
<Rand />
The element is created, but not used, and your function isn't called. The "your function isn't called" part may be surprising — it was to me when I started using React — but it's true:
const { Fragment } = React;
function Rand() {
console.log("Rand called");
return <Fragment>{Math.random()}</Fragment>;
}
console.log("before");
const element = <Rand />;
console.log("after");
// Wait a moment before *using* it
setTimeout(() => {
ReactDOM.render(
element,
document.getElementById("root")
);
}, 1000);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
How can I prevent in both cases to re-render/re-initialize the component?
If you do what you've done in your example, which is to take the mounted component out of the tree entirely, you're unmounting the component instance; when you put it back, your function will get called again, so you'll get a new value. (This is also why the version with the counter doesn't exhibit this behavior: the component instance remained mounted.)
If you want to memoize what it shows, one approach is to pass that to it as a prop, and memoize what you pass it:
const { useState, useMemo, Fragment } = React;
function Rand({text}) {
return <Fragment>{text}</Fragment>;
}
const App = () => {
const [show, setShow] = useState(true);
const working = useMemo(() => <Fragment>{Math.random()}</Fragment>, []);
const randText = useMemo(() => String(Math.random()), []);
return(
<Fragment>
<button
onClick={() => {
setShow(!show);
}}>
{show?"Hide":"Show"}
</button>
<br />
Working:
{show && working}
<br />
Also Working Now:
{show && <Rand text={randText} />}
</Fragment>
);
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
Source: stackoverflow.com
Related Query
- useMemo behaves different for inline component vs. normal component
- using same component for different route path in react-router v4
- React functional component - using inline functions for handlers affects performance?
- Creating Different mobile layout for a component in ReactJs
- Using the same component for different Routes with React Router
- React Router switch does not mount same component for different routes
- lodash , convert string from svg circle (properties and values separates with space) to object for spread in react component inline
- Can't trigger a search function for movie API project because useState is in a different component
- Different Navbar for a component in react router
- Two routes with different query strings for the same component
- Different props state for smart and dumb component
- only one child route displaying in react? displays component for a different route instead of its own
- route to different component for similar routes with react router
- How to display different navbar component for different reactjs pages
- showing a different component on state change and for loop React js
- How to handle desktop vs mobile layout for a component when the mobile design is VERY different (aka cannot make use of grid layout)?
- Stores for reusable React+Flux form component (one component for multiple forms with different fields)
- React routing for different parts of app like normal app for users and dashboard for admin
- Keyframes animation not working when multiple instances of a Component rendered with different props?Width used for animation depends on a prop value
- How I can create one component for different JSON files with the same structure
- Go to previous state or Re Render component for two different API functions in ReactJS
- react-router v3: How to load data for the component when the same route with different query params is loaded
- Rendering inline styles as well as pre-defined styles for React Component
- Redux: using different reducers for a component
- For different route, same react component does not get mounted
- How can I use different dynamic slug url for same component React js?
- How to render same react component for different routes with different value props?
- React.js generate dynamic routes for the same component with different data
- Different routes for same component
- React query error boundaries: how to give users different options depending on whether they are seeing the component for the second time
More Query from same tag
- How to change colour and position of Navbar using useEffect and useState?
- Tool for checking codestyle in JSX files
- React make variable go up randomly by a random value until it hits a threshold
- bufferGeometry and shadow react-three-fiber
- Shallow copy a React component with a provided store in Enzyme
- React: invoke props in a function
- Refining code: Is there a better way to map one (shorter) array to another (longer) array of objects in Javascript?
- React-Redux - Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions
- Making several API requests at once?
- React interaction between components
- React: Checkbox triggers rendering only once
- How to export a stateless functional component with styles in Reactjs
- React forwardRef: ref and other props
- where to place componentDidMount in order to change link Navbar color while scrolling in React / Gatsby?
- Material ui button does not take into consideration the css styles to override the default one
- How do I get tailwinds active breakpoint in JavaScript?
- Update another component when Formik form changes
- This plugin file is using both CommonJS and ES6 module systems together which we don't support
- Line 8: Parsing error: this is a reserved word
- React Problem with multiple export in Class Component
- Create Role Based Authorization in Auth0 and NextJS
- How to add text based on click which is outside the Editor component , to the Editor
- Add header in pdf
- Updating State when box is unchecked
- createContext hook not working for react components inside JSP
- How to concatenate React objects without JSX
- React Typescript property does not exist on type / IntrinsicAttributes & IntrinsicClassAttributes
- How to style/display this array in this way ? - CSS/Javascript
- Mobile browser positions elements as if the view is 360px wide, but renders images on the page at a higher resolution. How does this work?
- Unexpected token in valid RegEx when running webpack