score:30
Is it correct that this.setState in class components always cause a re-render, even when the new state value is identical to the previous?
If you set a valid value apart from returning null within setState, a re-render will always be triggered by react in a class component unless your component is a PureComponent or you implement shouldComponentUpdate
Is it correct that in function components with hooks, setState from useState only causes a re-render if the state value is different from the previous value?
For a functional component using useState
hook, the setter if called with the same state will not trigger a re-render. However for an occasional case if the setter is called immediately it does result in two renders instead of one
Is setting state with this.setState inside the render method of a class component, the same as setting state inside the function body of a function component with hooks?
Techincally yes, setting a state directly in render method will cause the function to trigger re-render in case of class component causing an infinite loop which is the case for functional components provided the state values are different. Regardless of that, it will still cause an issue because any other state update will be reverted back due to functional component calling state update directly
In a class component, if we set state in the render method an infinite loop will occur. This is because the class component does not care that the new state is the same as the previous state. It just keeps re-rendering on every this.setState.
Yes, hence its recommended not to call setState directly in render
In a function component with hooks however, setting state inside the function body (which runs at re-render similarly to the render method in class components) would not be an issue, because the function component just bails out of re-renders when it sees that the state is identical to the previous state.
Not 100% true, since you can trigger state update using previous value such that the previous and current value are not same.For example
setCount(count => count + 1);
In such a case, you component will still fall in an infinite loop
score:1
This is not a direct answer to the OP, but related and maybe helpful for some people new to React and/or Hooks and struggling with their side-effect and render timing.
Since it hasn't been mentioned here yet: In functional components rather than using the beforementioned (see comments of the accepted answer) ShouldComponentUpdate()
function, which is for class-based Components only, you would use the useEffect()
hook. With it you can tell your component when to run the side effects AND under which condition, e.g. when certain dependencies have changed.
In this example from the React docs, only when props.source
changed, the function will be executed.
useEffect(
() => {
const subscription = props.source.subscribe();
return () => {
subscription.unsubscribe();
};
},
[props.source],
);
Source: stackoverflow.com
Related Query
- What are the differences when re-rendering after state was set with Hooks compared to the class-based approach?
- What are the differences between Redux-Thunk and Redux-Promise when used with Axios apis?
- React functional stateless component, PureComponent, Component; what are the differences and when should we use what?
- Accessing the State of a Functional Component with React Hooks when Testing with Enzyme
- How to optimize React components with React.memo and useCallback when callbacks are changing state in the parent
- cant update context state when using hooks with a complex object to set providers value
- What is the right way for removing timers in React. When they are created after onClick function is executed
- What is the Mobx way to do handle set state with callbacks
- React Hooks: using useState inside useEffect doesn't set the state immediately after first rendering
- How can I make react render the new state modifications after I have updated the state with hooks and context
- React Hooks - What is the recommended way to initialize state variables with useState() from props
- When POSTing to the database, I'm getting a "Can't set headers after they are sent error"
- What is the proper way to concatenate strings with JavaScript (JSX) template literals when one is after comma
- What is the issue when consuming an state in child component after useEffect?
- Updating component state by Listening to socket events inside react hooks or handling them inside middleware? what are the downsides of each one?
- Making the state of a component affect the rendering of a sibling when components are rendered iteratively
- What state represents the loading or data not fetched yet state when using enabled with useQuery in react-query?
- Cannot set headers after they are sent to the client (error when i'm striking axios post requrest)
- React.js: Cancel button is cancelling editing but leaving the state with the changed value after editing was started
- How to set an initial state with hooks when data finish to load
- When I set state via useState in parent component, my props in the child I'm passing down to are undefined
- React component is picking the old state when used with hooks
- What does it mean when there are two functions with the 'arrow function indicator' between them?
- Why when the state is updated the changes in the rendering are not updated?
- What are the differences between useEffect versus componentDidMount/componentWillUnmount? What are the differences between hooks and this.setState?
- Want to send JWT token in headers along with data using axios but getting this error : Cannot set headers after they are sent to the client
- Getting an error "A non-serializable value was detected in the state" when using redux toolkit - but NOT with normal redux
- Set state when testing functional component with useState() hook
- Is there any way to see names of 'fields' in React multiple state with React DevTools when using 'useState' hooks
- Invalid hook call. Hooks can only be called inside of the body of a function component when apply style to class base component with material-ui
More Query from same tag
- How to implement a mediaquery inside styledcomponents?
- why show error[ You must pass a component to the function returned by connect. Instead received undefined] in react redux
- Authorize React Components for Users by Role/Permissions
- ImportError: cannot import name 'OrderDetailView' from 'core.api.views' in Django and ReactJs
- Why React hook useEffect runs endlessly?
- How to format Date input?
- How to add multiple classNames to nextjs elements
- Update a redux array of object but not re-render the component
- I can't deal with SSR React
- how useState really work when state change and state not change
- TypeScript, VSCode: keyof type not working as expected when switching to insider version of vscode
- Delay a loop with timeout in react js
- React Next app not working as expected, most likely hook updating issue
- Webpack Dev Server Config - contentBase not working
- React Native ListView TextInput locks up from performance optimization rendering
- Select with chip input not displaying the selected value
- react-select map options population
- Server Error TypeError: _nextProps.children is not a function _document getInitialProps
- How pass state and props between components more efficiently
- Has problems when pass a component as React setState value?
- React Error Boundaries cannot work, just break
- React: How to read external onChange events
- NextJS SCRIPT1028 - caused by destructuring in object in Edge
- React.js - Array.unshift() not updating array on front-end
- How to resolve mutating state directly issue
- React router and context
- React how to toggle onclick to false after you already clicked?
- Can I access the props or state of a Pagination component being generated by an Ant Design Table?
- Can't page break to work without messing up the table formatting
- Using React.setState in componentDidMount() for data returned within nested promises?