The functional component will be redrawn every time the parent displays it, regardless of whether the details have changed or not.
However, using the high-order React.memo
functional components can get the same shouldComponentUpdate
that is used in PureComponent
https://reactjs.org/docs/react-api.html#reactmemo.
You can simply wrap your functional component in React.memo
when exporting, as shown here.
So
const SomeComponent = (props) => (<div>HI</div>) export default SomeComponent
Maybe instead
const SomeComponent = (props) => (<div>HI</div>) export default React.memo(SomeComponent)
example
The following example shows how this affects rendering.
A parent component is just an ordinary functional component. It uses new reaction handlers to handle some state updates.
It just has some tick
state that serves only to give some hint about how often we redefine props, while it causes a re-rendering of the parent component twice per second.
Next, we have a clicks
state that tells us how often we clicked a button. This is what we send to children. Therefore, they should ONLY review if the number of clicks changes, if we use React.memo
Now notice that we have two different kinds of children. One is wrapped in memo
and the other is not. Child
that is not wrapped will be redrawn each time the parent redraws. MemoChild
packed MemoChild
will be redrawn only when the click property changes.
const Parent = ( props ) => { // Ticks is just some state we update 2 times every second to force a parent rerender const [ticks, setTicks] = React.useState(0); setTimeout(() => setTicks(ticks + 1), 500); // The ref allow us to pass down the updated tick without changing the prop (and forcing a rerender) const tickRef = React.useRef(); tickRef.current = ticks; // This is the prop children are interested in const [clicks, setClicks] = React.useState(0); return ( <div> <h2>Parent Rendered at tick {tickRef.current} with clicks {clicks}.</h2> <button onClick={() => setClicks(clicks + 1)}> Add extra click </button> <Child tickRef={tickRef} clicks={clicks}/> <MemoChild tickRef={tickRef} clicks={clicks}/> </div> ); }; const Child = ({ tickRef, clicks }) => ( <p>Child Rendered at tick {tickRef.current} with clicks {clicks}.</p> ); const MemoChild = React.memo(Child);
You can check the example here https://codepen.io/anon/pen/ywJxzV