Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Stateful Components without classes

In React, we can write components as pure functions. However, the problem with this is that you can't use it as stateful components because of the lack of lifecycle hooks and state. So, I wonder if is there any way to create stateful components without using classes.

Something that I found is the createClass helper. But, React has moved this helper into their own package in the release 15.5.0, link. Also, they recommend that you migrate them to JavaScript classes because classes are now the preferred way to create components in React. Therefore, I don't think that using this helper could be a good idea.

On the other hand, Facebook recommends the use of High Order Components (HOCs) which is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature. But, I couldn't find a way to create common stateful components without classes.

Has anyone gone through this? Is there any way to use React as a some purely functional solution?

like image 339
mattias Avatar asked Jul 30 '17 20:07

mattias


People also ask

Can we use state without a class in React?

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. We'll start learning about Hooks by comparing this code to an equivalent class example.

Do you need class components in React?

Short answer, yes. React class components are rearly used in modern React development but we still need to know them in case we need to work on old legacy projects. If you want to embrace modern React, then you should use function components with hooks.

What are stateful components in React?

In React, a stateful component is a component that holds some state. Stateless components, by contrast, have no state. Note that both types of components can use props. In the example, there are two React components. The Store component is stateful and the Week component is stateless.

Can we define state without constructor in React?

You can also use state in React function components (without a constructor), but using higher-order components or render prop components.


1 Answers

React supports this since version 16.8. From the documentation:

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

A simple example:

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

For an example of how to use lifecycles, check out useEffect

like image 65
Karamell Avatar answered Oct 22 '22 00:10

Karamell