I have a class that needs to get the size of a DOM element. It works well, but when I resize the window it doesn't update until I change the state in my app, forcing a rerender. I've tried adding this.forceUpdate to a 'resize' event listener in componentDidMount(), but it didn't work. Perhaps I did something wrong? Ideally I'd like to avoid using this.forceUpdate for perfomance implications anyway. Any work arounds for this? Thanks in advance!
My code:
class MyComponent extends React.Component {
state = { x: 0, y: 0 }
refCallback = (element) => {
if (!element) {
return
}
const { x, y } = element.getBoundingClientRect()
this.setState({ x, y })
}
render() {
console.log('STATE:', this.state) // Outputs the correct x and y values.
return (
<div ref={this.refCallback}>
<button>Hello world</button>
</div>
)
}
}
If you want to measure some element in your component whenever the window resizes, it's going to look something like this:
class MyComponent extends React.Component {
state = {
x: 0,
y: 0,
};
element = React.createRef();
onWindowResize = () => {
if (this.element.current) {
const {x, y} = this.element.current.getBoundingClientRect();
this.setState({x, y}, () => {
console.log(this.state);
});
}
};
componentDidMount() {
window.addEventListener('resize', this.onWindowResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.onWindowResize);
}
render() {
return (
<div ref={this.element}>
<button>Hello, World</button>
</div>
);
}
}
The trick here is that your ref callback is only called once, when the element is initially added to the DOM. If you want to update state whenever you resize the window, you're going to need a 'resize' event handler.
That happening because:
From the React documentation:
Adding a Ref to a DOM Element
React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.
React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts.
So, that's why when you refresh you get the value. To overcome the problem you can do something like this:
import React from "react";
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
this.state = {
x: 0,
y: 0
};
}
updateDimensions = () => {
if (this.myRef.current) {
const {x, y} = this.myRef.current.getBoundingClientRect();
this.setState({ x, y });
}
};
componentDidMount() {
window.addEventListener("resize", this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions);
}
render() {
console.log("STATE:", this.state); // Outputs the correct x and y values.
return (
<div ref={this.myRef}>
<button>Hello world</button>
</div>
);
}
}
export default MyComponent;
Hope this works for you.
I would like to develop a new feature, which previously would have lived in a higher order component, using hooks. However, since according to the React Documentation:
"You can’t use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree."
So let's say I have some existing class component ExistingComponent that I want to extend with additional functionality, say, listening to window.resize. I would expect to do it like this.
// Existing Component
export class ExistingComponent extends React.Component {
render() {
return <div>I exist!</div>;
}
}
// Hook
export const useWindowResize = () => {
function resize() {
console.log('window resized!');
}
useEffect(() => {
window.addEventListener('resize', resize);
return function cleanup() {
window.removeEventListener('resize', resize);
};
});
};
// HOC
export const withWindowResize = component => {
useWindowResize();
return component;
};
// Extended Component
export const BetterComponent = withWindowResize(ExistingComponent);
However, this fails with Uncaught Invariant Violation: Hooks can only be called inside the body of a function component. I do use react-hot-loader, but I am still able to use hooks in component functions that don't return a class component. Also, I can remove the useWindowResize() from the function and it renders as expected.
I am also able to render the example provided in the docs, so I know it's not a problem with hooks generically:
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Is this the wrong approach?
You can return a new function component from your withWindowResize HOC in which you call the hook and spread the props on the component you pass in.
You can also pass an empty array as second argument to useEffect to only have it run once after the initial render.
const { useEffect } = React;
class ExistingComponent extends React.Component {
render() {
return <div>I exist!</div>;
}
}
const useWindowResize = () => {
useEffect(() => {
function resize() {
console.log('window resized!');
}
window.addEventListener('resize', resize);
return () => {
window.removeEventListener('resize', resize);
};
}, []);
};
const withWindowResize = Component => {
return (props) => {
useWindowResize();
return <Component {...props} />;
}
};
const BetterComponent = withWindowResize(ExistingComponent);
ReactDOM.render(<BetterComponent />, document.getElementById("root"));
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>
I have a server side rendering react app (because I need Facebook Seo as well).
A part of my app requires to get window.innerWidth.
I have been searching for a long time, most of them says you cannot find window on server side, so you need to do rendering on client side as well.
I'm not sure how things work, I have componentdidmount but my windowWidth is forever 0.
After server rendering, our bundle.js will kick in and window on client side will work right? How come it's still 0?
state = {
windowWidth: 0
}
handleResize(){
this.setState({windowWidth: window.innerWidth});
}
componentDidMount () {
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
}
render() {
return (<div>{this.state.windowWidth}</div>)
}
The problem is that you attaching a function to set the new width to a "resize" listener which means only when you resize the screen the new width will added to state. You need to set the width inside componentDidMount and then you will have it width right on mount.
sandbox
CODE:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
windowWidth: 0
};
}
handleResize = () => {
this.setState({ windowWidth: window.innerWidth });
};
componentDidMount() {
this.setState({ windowWidth: window.innerWidth });
window.addEventListener("resize", this.handleResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
render() {
return (
<div>{this.state.windowWidth && <p>{this.state.windowWidth}</p>}</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Instead of writing my components inside a class, I'd like to use the function syntax.
How do I override componentDidMount, componentWillMount inside function components?
Is it even possible?
const grid = (props) => {
console.log(props);
let {skuRules} = props;
const componentDidMount = () => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
};
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
Edit: With the introduction of Hooks it is possible to implement a lifecycle kind of behavior as well as the state in the functional Components. Currently
Hooks are a new feature proposal that lets you use state and other
React features without writing a class. They are released in React as a part of v16.8.0
useEffect hook can be used to replicate lifecycle behavior, and useState can be used to store state in a function component.
Basic syntax:
useEffect(callbackFunction, [dependentProps]) => cleanupFunction
You can implement your use case in hooks like
const grid = (props) => {
console.log(props);
let {skuRules} = props;
useEffect(() => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
}, []); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners, replicating the behavior of componentWillUnmount:
Eg: componentWillUnmount
useEffect(() => {
window.addEventListener('unhandledRejection', handler);
return () => {
window.removeEventListener('unhandledRejection', handler);
}
}, [])
To make useEffect conditional on specific events, you may provide it with an array of values to check for changes:
Eg: componentDidUpdate
componentDidUpdate(prevProps, prevState) {
const { counter } = this.props;
if (this.props.counter !== prevState.counter) {
// some action here
}
}
Hooks Equivalent
useEffect(() => {
// action here
}, [props.counter]); // checks for changes in the values in this array
If you include this array, make sure to include all values from the component scope that change over time (props, state), or you may end up referencing values from previous renders.
There are some subtleties to using useEffect; check out the API Here.
Before v16.7.0
The property of function components is that they don't have access to Reacts lifecycle functions or the this keyword. You need to extend the React.Component class if you want to use the lifecycle function.
class Grid extends React.Component {
constructor(props) {
super(props)
}
componentDidMount () {
if(!this.props.fetched) {
this.props.fetchRules();
}
console.log('mount it!');
}
render() {
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
}
Function components are useful when you only want to render your Component without the need of extra logic.
You can use react-pure-lifecycle to add lifecycle functions to functional components.
Example:
import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';
const methods = {
componentDidMount(props) {
console.log('I mounted! Here are my props: ', props);
}
};
const Channels = props => (
<h1>Hello</h1>
)
export default lifecycle(methods)(Channels);
You can make your own "lifecycle methods" using hooks for maximum nostalgia.
Utility functions:
import { useEffect, useRef } from "react";
export const useComponentDidMount = handler => {
return useEffect(() => handler(), []);
};
export const useComponentDidUpdate = (handler, deps) => {
const isInitialMount = useRef(true);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
return;
}
return handler();
}, deps);
};
export const useComponentWillUnmount = handler => {
return useEffect(() => handler, []);
};
Usage:
import {
useComponentDidMount,
useComponentDidUpdate,
useComponentWillUnmount
} from "./utils";
export const MyComponent = ({ myProp }) => {
useComponentDidMount(() => {
console.log("Component did mount!");
});
useComponentDidUpdate(() => {
console.log("Component did update!");
});
useComponentDidUpdate(() => {
console.log("myProp did update!");
}, [myProp]);
useComponentWillUnmount(() => {
console.log("Component will unmount!");
});
return <div>Hello world</div>;
};
Solution One:
You can use new react HOOKS API. Currently in React v16.8.0
Hooks let you use more of React’s features without classes.
Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.
Hooks solves all the problems addressed with Recompose.
A Note from the Author of recompose (acdlite, Oct 25 2018):
Hi! I created Recompose about three years ago. About a year after
that, I joined the React team. Today, we announced a proposal for
Hooks. Hooks solves all the problems I attempted to address with
Recompose three years ago, and more on top of that. I will be
discontinuing active maintenance of this package (excluding perhaps
bugfixes or patches for compatibility with future React releases), and
recommending that people use Hooks instead. Your existing code with
Recompose will still work, just don't expect any new features.
Solution Two:
If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a function component.
Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).
// taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33
function RenderlessComponent() {
return null;
}
export default lifecycle({
componentDidMount() {
const { checkIfAuthed } = this.props;
// Do they have an active session? ("Remember me")
checkIfAuthed();
},
componentWillReceiveProps(nextProps) {
const {
loadUser,
} = this.props;
// Various 'indicators'..
const becameAuthed = (!(this.props.auth) && nextProps.auth);
const isCurrentUser = (this.props.currentUser !== null);
if (becameAuthed) {
loadUser(nextProps.auth.uid);
}
const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
if (shouldSetCurrentUser) {
const currentUser = nextProps.users[nextProps.auth.uid];
if (currentUser) {
this.props.setCurrentUser({
'id': nextProps.auth.uid,
...currentUser,
});
}
}
}
})(RenderlessComponent);
componentDidMount
useEffect(()=>{
// code here
})
componentWillMount
useEffect(()=>{
return ()=>{
//code here
}
})
componentDidUpdate
useEffect(()=>{
//code here
// when userName state change it will call
},[userName])
According to the documentation:
import React, { useState, useEffect } from 'react'
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
});
see React documentation
Short and sweet answer
componentDidMount
useEffect(()=>{
// code here
})
componentWillUnmount
useEffect(()=>{
return ()=>{
//code here
}
})
componentDidUpdate
useEffect(()=>{
//code here
// when userName state change it will call
},[userName])
You can make use of create-react-class module.
Official documentation
Of course you must first install it
npm install create-react-class
Here is a working example
import React from "react";
import ReactDOM from "react-dom"
let createReactClass = require('create-react-class')
let Clock = createReactClass({
getInitialState:function(){
return {date:new Date()}
},
render:function(){
return (
<h1>{this.state.date.toLocaleTimeString()}</h1>
)
},
componentDidMount:function(){
this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
},
componentWillUnmount:function(){
clearInterval(this.timerId)
}
})
ReactDOM.render(
<Clock/>,
document.getElementById('root')
)
if you using react 16.8 you can use react Hooks...
React Hooks are functions that let you “hook into” React state and lifecycle features from function components...
docs
import React, { useState, useEffect } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
const [count2, setCount2] = useState(0);
// componentDidMount
useEffect(() => {
console.log("The use effect ran");
}, []);
// // componentDidUpdate
useEffect(() => {
console.log("The use effect ran");
}, [count, count2]);
// componentWillUnmount
useEffect(() => {
console.log("The use effect ran");
return () => {
console.log("the return is being ran");
};
}, []);
useEffect(() => {
console.log(`The count has updated to ${count}`);
return () => {
console.log(`we are in the cleanup - the count is ${count}`);
};
}, [count]);
return (
<div>
<h6> Counter </h6>
<p> current count: {count} </p>
<button onClick={() => setCount(count + 1)}>increment the count</button>
<button onClick={() => setCount2(count2 + 1)}>increment count 2</button>
</div>
);
};
export default Counter;
The problem is roughly summarized in the comments in the code snippet. When I bind this._setSize in constructor, it never knows about this.container — even when called in componentDidMount. What am I doing wrong? Thanks!
export default class MyComponent extends React.Component {
constructor () {
super()
this._setSize = this._setSize.bind(this)
}
componentDidMount () {
const container = this.container // <div></div> :)
this._setSize()
window.addEventListener('resize', this._setSize)
}
componentWillUnmount () {
window.addEventListener('resize', this._setSize)
}
_setSize () {
const container = this.container // undefined :(
const containerSize = {
x: container.offsetWidth,
y: container.offsetHeight
}
this.setState({ containerSize })
}
render () {
return (
<div ref={node => this.container = node}>
</div>
)
}
}
Within each re-render you are creating and passing new instance of function to setup container ref. The previous function is then called with null. Therefore it might happen that you accidently set this.container to null:
<div ref={node => this.container = node}>
When you pass here component instance method instead of inline function, it is called once with reference and second time with null during component unmount. E.g.:
// dont forget to bind it in constructor
onContainerRef (node) {
// furthermore you can even check if node is not null
// if (node) { ...
this.container = node
}
// ... in render
<div ref={this.onContainerRef}>
You can read more in docs.
I fixed your code and it's working now: see working DEMO
What was the problem?
componentWillUnmount () {
window.addEventListener('resize', this._setSize)
}
You didn't remove event listener from window because in componentWillUnmount you have addEventListener instead of removeEventListener. If you have any conditional rendering of the component, on resize event _setSize will be also called.
To illustrate this problem, play with the broken demo and click on Toggle button and look at output: see broken DEMO