1) Use State Correctly
State is an essential aspect of React and should be used wisely. It's recommended to keep the state minimal and only store values that change within the component.
class Example extends React.Component {
state = { count: 0 }
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={this.handleClick}>Click me</button>
</div>
);
}
}
2) Use Props Correctly
Props are used to pass data from one component to another. It's recommended to keep the component pure, i.e., the component should only receive props and render the view.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
3) Use the Right Tools
React provides several tools to make development easier, such as React Developer Tools (browser extension) and Create React App. Make sure you're using the right tools for the job.
4) Write Clean Code
It's important to write clean and maintainable code, as it helps to reduce bugs and make it easier to understand and debug. A good rule of thumb is to follow the Airbnb JavaScript style guide.
const names = ['Sara', 'Cahal', 'Edite'];
const namesList = names.map((name, index) => (
<li key={index}>{name}</li>
));
5) Use Conditional Rendering
In React, it's possible to conditionally render components based on certain conditions. This can be done using if-else statements or ternary operators.
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
ReactDOM.render(
<Greeting isLoggedIn={false} />,
document.getElementById('root')
Top comments (0)