2019-05-01+net

(Brent) #1

React


Next we can create our main app.js file – or index.js
if you like:


import React from “react”;
import ReactDOM from “react-dom”;
import MyContextProvider from “./Context”;
import Module1 from “./Module1”;
import Module2 from “./Module2”;
import “./styles.css”;
function App() {
return (




Hello Context






);
}

const rootElement = document.getElementById(“root”);
ReactDOM.render(, rootElement);


As you can see from the code, the two modules that
we’ve created don’t have any props passed down
from the parent. Instead all of this functionality is
taken care of with the Context provider and children
inside that.
But wait! There’s more we can do to boost
performance here.


REDUCING RE-RENDERING
First of all, let’s explain that term. Re-rendering
is what happens when the component you’re using
is updated. This has performance implications,
especially for interactions like dragging (think
sliders) and inputting text. Without proper
care, users could notice lagginess and be put off
from using your site. And the potential for lag
or unresponsiveness increases with complexity
(because more re-rendering will happen).


I have found this to be especially true on devices
that are from the cheaper end of the market.
JavaScript parsing times can dramatically increase
on low- and mid-range devices that don’t run recent
versions of Chrome or Firefox. A huge group of
people could be impacted by this, severely affecting
your conversions.
One method of reducing re-renders that I’ve found
to be effective is by using my context’s state to hold
functions as well.
By moving onItemSelect out of the class and into the
state object, we can call it in a similar way (context.
onItemSelect becomes context.state.onItemSelect in our
modules) and avoid a component update.

TRY USING CONTEXT TODAY
Have you ever found yourself writing props={props}
all over the place or using the spread operator to
pass props down anonymously (like this: <MyModule
{...props}/>)? Then you might just find that Context
offers you a way out of the hole you have drilled
yourself into.
If you’re looking for a way to reduce the potential
for complexity in a project or reduce performance
bottlenecks and you don’t need the extra features
that a dedicated state management tool or client-side
GraphQL server would provide, chances are Context
could be the tool for the job.
It’s true that Context isn’t going to fit everyone’s
use case but then it was never meant to. However, it
is still a very useful API with some practical features
that you might find give your code a little more...
well, context.
Remember to view the working code on
CodeSandbox (https://codesandbox.io/s/0pl62xq030).

Top You don’t have to rely
on your savvy to detect
re-rendering bottlenecks –
the React Developer Tools
can help

“Re-rendering is what


happens when the


component you’re


using is updated. This


has performance


implications”

Free download pdf