How much JavaScript to learn before learning React? Let’s walk through seven useful skills that any professional React developer needs to learn.
In this material, we will consider what tools and key skills a React-developer should have to keep abreast of the industry and make a good impression at a job interview.
Knowledge of JavaScript
React is built on top of JavaScript. First of all, people who want to learn React need to understand how well they know JavaScript itself.
Very often developers ask questions that show they don’t know the basics of JavaScript. Whereas questions about the React ecosystem come up much less frequently. That’s why we recommend deepening your knowledge of JavaScript first, and then going back to React.
Using the State Manager
React.js doesn’t have a built-in State Manager. For a long time Redux library was used as a standard, but it doesn’t fulfill this role very well – you have to write a lot of boilerplate code when working with it, there are no tools to manage asynchronous behavior and side-effects.
This is how other State Managers started to appear. The Redux developers took their shortcomings into account and presented the Redux Toolkit library, which was well received by frontend developers.
Redux Toolkit — библиотека поверх Redux. Она дает возможность добиться того же, что и Redux, но с Redux Toolkit вам придется писать намного меньше кода, чем c Redux. Кроме того, Redux Toolkit использует внутри себя Immer.js, поэтому не нужно думать над иммутабельностью данных, т.е использовать деструктуризацию, создавая каждый раз новые объект состояния в редьюсерах.
Еще одна довольно перспективная библиотека — MobX. Бизнес логика MobX отличается от Redux. Не стоит забывать и про Effector, которую создали выходцы из СНГ.
На сегодняшний день эти три State Managers являются самыми популярными. Все три библиотеки очень хорошо справляются со своей задачей, но мы обычно используем либо Redux Toolkit, либо Effector.
React Hooks
React Hooks пришли к нам в гости с 16.8 версии и останутся с нами надолго. Если вы про них сейчас слышите впервые, то, сначала вам стоит ознакомиться с ними в официальной документации React.
Хуки — это просто еще один способ описывать логику ваших компонентов. Он позволяет добавить к функциональным компонентам некоторые возможности, ранее присущие только классовым компонентам.
Большинство людей на собеседовании плывут на вопросах про хуки, хотя вся информация есть в документации. Всем кто, хочет развиваться, непременно нужно хотя бы посмотреть как они работают, а с опытом работы можно понять технологию глубже.
На использование хуков накладываются некоторые ограничения, которые их отличают от обычных функций. В первую очередь их нельзя использовать в классовых компонентах. Хуки нельзя вызывать внутри циклов, условий. Это ограничение накладывает сам React, чтобы получить возможность отслеживать, какие хуки были вызваны.
Когда хуки только появились, мы в Holyweb экспериментировали на них, писали новые компоненты и смотрели, что из этого выйдет. Когда все хорошо получалось, мы использовали их дальше, писали на них новые фичи. Для тех, кто до сих пор не использовал React Hooks, я бы рекомендовал это попробовать — с ними очень легко описывать нужную логику, они делают код чистым и более понятным.
Многих волнует вопрос, стоит ли переписывать проект по новой, потому что появились хуки. Я бы не сказал, что перформанс значительно возрастет или упадет от таких действий. Если вам понравятся хуки, то пишите новые фичи вашего проекта на них. Переписать старые куски всегда вы успеете.
Давайте посмотрим примеры на хуках.
Сделаем простой Counter.
Вот код с использованием классового компонента:
class App extends React.Component {
state = {
counter: 0
};
onIncrement = () => {
this.setState((state) => {
return {
counter: state.counter + 1
}
});
};
onDecriment = () => {
this.setState((state) => {
return {
counter: state.counter - 1
}
});
};
render() {
return (
<div>
<button onClick={this.onIncrement}>+</button>
<button onClick={this.onDecriment}>-</button>
<div>Counter: {this.state.counter}</div>
</div>
);
}
}
And here is the code using the function component and hooks:
function App () {
const [counter, toggleCounter] = React.useState(0)
const onIncrement = () => {
toggleCounter(counter => counter + 1)
}
const onDecriment = () => {
toggleCounter(counter => counter - 1)
}
return (
<div>
<button onClick={onIncrement}>+</button>
<button onClick={onDecriment}>-</button>
<div>Counter: {counter}</div>
</div>
);
}
You can see that code on hooks is cleaner and clearer.
Server-Side Rendering
There are several popular SSR solutions available right now. In our first projects where we used SSR, we had a completely custom solution. Over time, we began to explore and use off-the-shelf solutions. Each of them has its pros and cons. For example, we use Razzle on one of our current projects, and Next.js on another.
Next.js is a popular lightweight framework for static and server-side applications using React. It includes out-of-the-box styling and routing solutions and assumes you’re using Node.js as your server environment. What Next doesn’t quite have is that in some cases it dictates the architecture and how to build applications. But that’s a matter of taste and personal preference.
Razzle is a server-side rendering framework, more flexible than Next.js, but not necessarily customizable.
If you’re serious about SSR, we recommend that you take a close look at the following products and try to get the most out of your hands-on experience:
- js (React-based);
- js (Vue-based);
- Gatsby (React-based);
- Gridsome (Vue-based).
Common mistakes in learning React
The main mistake most developers make is not carefully reading the documentation. For example, one of our developers confessed that he did not read the documentation well and started usingCallback everywhere when it was not necessary. Only later did he realize this when he started rereading the documentation.
The questions that people ask in chat rooms and core communities, most often already have answers in the documentation – you just need to read it carefully.
In addition to the library itself, the specialist must know such technologies as HTML, CSS, JavaScript, npm, Git, Babel, WebPack, Redux. Skills in working with other tools can also come in handy, but it already depends on the job.
But the main thing is not the hard skills a person has already mastered, but how well he knows how to learn. If a developer has this skill, it will not be difficult for him to prepare for the interview, come to the company and learn everything he needs in the course of work.