Props and state are an integral part of any React application. When working with React you will find yourself passing props over and over again. At some point, you may start noticing that the process is quite inefficient overall. There are a couple of tricks that you can use to improve the code quality of your application. Let’s explore them together.
JS Expressions
You can pass any JS expression as long as it’s surrounded by curly braces. Let’s take a look at how you can use it efficiently.
import User from './User'
function App() {
return (
<div>
<User />
</div>
);
}
export default App;
For illustration purposes, I have written a simple App.js component that uses User component. The exact body of the User is irrelevant.
import { useState } from 'react'
import User from './User'
function App() {
const [age, setAge] = useState(17)
return (
<div>
<User
ageInThreeYears={age + 3} <== 20
isUnderage={age < 18} <== true
/>
</div>
);
}
export default App;
We added a piece of state called age and initialised it to 17. We’re then using it to pass relevant props to the User. The first component ageInThreeYears will evaluate the expression age + 3 (which is 20), whereas the second one will evaluate the expression to boolean (true, since 17 is less than 18).
By using this technique we can easily define props that depend on pieces of state.
Template Literals
We can also use template literals in a similar fashion to determine the strings in the parent component.
import { useState } from 'react'
import User from './User'
function App() {
const [age, setAge] = useState(17)
return (
<div>
<User
message={`This year I turned ${age}, next year I'll be ${age + 1}`}
/>
</div>
);
}
export default App;
The message prop will evaluate to This year I turned 17, next year I’ll be 18
Default
Another useful property is that props that don’t receive any value default to true. This is particularly useful when the child component expects flag props to determine some logic.
import { useState } from 'react'
import User from './User'
function App() {
const [age, setAge] = useState(17)
return (
<div>
<User
isUnderage <== true
isStudying <== true
hasDrivingLicense={false} <== false
/>
</div>
);
}
export default App;
Spreading
When passing properties of objects as props, we can simply spread the object. Both of the below are actually receiving the same props.
import User from './User'
function App() {
const user = {
name: 'Tommy',
surname: 'Smith'
}
return (
<div>
<User name={user.name} surname={user.surname} />
<User {...user} />
</div>
);
}
export default App;
💬 Leave a comment