React
React is a great tool to have, but at times can be overused and often something simpler would work fine.
For example, we often see people ask for a React frontend on a WordPress website, when in fact a standard PHP WordPress installation would work much better.
It’s also worth remembering that if React isn’t server-side rendered (SSR), then the SEO will be very low down. So take that into consideration before jumping into a project with React.
That said, React is great, and if you find yourself answering yes to any of the following answers, then it’s probably a good fit.
- Does the site need to be accessible offline?
- Does the site need a very smooth, stateful interface?
- Will the project be big enough to use React over a lighter weight competitor, such a Vue?
- Will the project need to remain performant in the browser whilst rendering a lot of data?
- Is this going to be cross-compiled into a native application?
Components
Until the introduction of React Hooks, components that needed to handle state were written in an ES6 class. Whilst there are times that you still need to do this (Error Boundaries, we suggest that all new components are written as functional components using hooks.
This is a class component that implements a search box with state:
import React, {Component} from 'react'
class SearchBox extends Component {
constructor(props) {
super(props)
this.state = {
term: '',
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(e) {
this.setState({
term: e.target.value,
})
}
render() {
const {term} = this.state
return (
<div className="search-box">
<input
onChange={this.handleClick}
value={term}
/>
</div>
)
}
}
This is the same component, but written as a functional component using hooks:
import React, {useState} from 'react'
const SearchBox = () => {
const [term, setTerm] = useState('')
const handleClick = (e) => {
setTerm(e.target.value)
}
return (
<div className="search-box">
<input
onChange={handleClick}
value={term}
/>
</div>
)
}
As you can see, writing it as a functional component and using hooks, makes the code a lot more concise and easier to read.
State
State is how React stores any data and is possibly the most important React concept to understand. State exists on a single component, but can be passed to others via its props. We can also pass state back up (called lifting the state) which can be useful when we want to store our state in a single place.
Lifting State
Take a look at this form component:
import React, {useState} from 'react'
import InputField from './InputField'
const NewsletterForm = () => {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const handleNameUpdate = (e) => {
setName(e.target.value)
}
const handleEmailUpdate = (e) => {
setEmail(e.target.value)
}
const handleSubmit = (e) => {
e.preventDefault()
const data = {
name,
email,
}
console.log(data)
}
return (
<form onSubmit={handleSubmit}>
<InputField
label="Name"
value={name}
handler={handleNameUpdate}
/>
<InputField
label="Email"
value={email}
handler={handleEmailUpdate}
/>
<button type="submit">
Subscribe
</button>
</form>
)
}
Hopefully you can see what we’re doing in a broad sense:
- Initialising our state hooks for name and email
- Declaring our handlers for events
- Returning the render method of the component
Let’s break down that render section slightly. We’re returning a form with an event handler that will
simply console.log()
our form values. Within that form we have a button for submitting it as well as rendering two
more React components. These are the <InputField/>
components that we can see imported on line 2.
The <InputField/>
components take a few props:
- label which will display within our label
- value which is the current value of that input
- handler which is a function to handle the change event within the component.
The actual <InputField/>
may look something like this:
import React from 'react'
const InputField = ({label, value, handler}) => (
<>
<label for={`${label.toLowerCase()}_input`}>
{label}
</label>
<input
id={`${label.toLowerCase()}_input`}
type="text"
value={value}
onChange={handler}
/>
</>
)
This is a pretty simple component, it just renders a label and an input, the magic is that it uses the handler that was
passed in via the props as the onChange
handler. That means that when the input changes, the value is actually passed
up to the parent <NewsletterForm/>
component and saved into the state there.
Other State Management Solutions
Sometimes you can just rely on state lifting in a React application, especially if it’s just something small. When the application grows though, you’ll need something more robust. Luckily, React has a few options. Firstly you have the context API, this is native within React and should be your first port of call. Context allows you to split your state into modules and group data that are related to a single context.
If the context API doesn’t do it for you, you can also give Redux a try. Redux is a state container for JavaScript apps (not just React) but has some very powerful React integrations that can really help with state management. Look into the react-redux package, and it’s also worth looking at the Redux Toolkit which gives you a sensible set of defaults and helps remove a lot of the config steps.
Server Side Rendering
Server side rendering (SSR) is the process of running your React application on a NodeJS server, rather than in the browser. This enables the browser to download full HTML rather than JS, which is great for SEO.
Server side rendering does pose some problems as you have no access to the window
object and many third-party
libraries won’t have been tested with SSR. That’s why you need to think carefully about whether React is the right tool
for the job, or if you could make do with a standard PHP build.
If you do decide to go down the SSR route with React, the most well known framework is Next.js so I’d start by looking at the documentation there.
If you’re looking at SSR the front end of a headless WordPress site, then it may pay to take a look at Frontity which seems to have been specifically built for this use-case.
More Info
React is a huge subject so your best bet is to read up about it. You can find some useful links below: