React & Redux - container component inside a presentational component? - javascript

I know this might be a little opinion-based question, but I think an important one.
In short, is it good practice to have react container components inside a react presentational component? What would you say could be the benefits and disadvantages of this practice of having container components inside a react presentational component?
I think that presentational components should be dummy: They take in props, and behave according to them, and nothing else affects them. They behave expectedly when given certain props, and nothing outwhere should affect their behaviour.
What could be the problem then having container component(s) inside a presentational component? Well, as container components usually have access to the (global) store (in redux), you cannot know simply from the props of the presentational component, that how the component will behave. Because the store will affect to the behaviour of the container component, and as it is included in the presentational component, then the presentational component is no longer a dummy component. What do you think?

I assume that by presentational component you are referring to a ReactJS functional component?
If so, I do not see a problem with this approach. The resulting component wouldn't be purely presentational, but it would do the job of defining the composition of the component(s) it renders.
Depending on the context, this could be exactly regards you need.
Rather than trying to build an application starting with presentational components, I prefer to take the approach of first scaffolding the bulk of my application and then refactor what I need to into presentational components.

Related

React pure component with hooks and state

I'm struggling about what may be a good way to implement components in React with a good coding pattern.
Normally I know the idea of presentational and container components: the presentational only shows html and receive everything from props (data and callbacks); the container orchestrate the presentationals retrieving and mutating data and passing it to them by props.
Now I'm using redux with redux toolkit and rtk query, with hooks.
Following that approach, the container component should be the only one allowed to useSelector and useDispatch and useQuery. But I find a lot easier and cleaner allowing the presentationals to select and fetch and dispatch what they really need, instead of making a giant container component which manage all the data for its children with a huge list of state and fetch access. This is true especially for lists, where it is a lot easier and cleaner just letting each child to retrieve its own data (fetched or from state), or for deeply nested presentationals.
However I'm mixing up container components with fake presentationals which anyway retrieve something when it is easier and true presentationals maybe for general and totally reusable components. Also the components tree is very messy (like container->fake presentational->container->fake presentational->true presentational->true presentational ...).
At the end I feel like I don't have good rules and the code is messed up.
Are container and presentation components still a good coding style which follows a best practice pattern but in the world of hooks and redux?
The React Container Pattern advocated by Dan Abramov has for all intents and purposes been deprecated since the introduction of React hooks in 2018.
See Dan's blog entry Presentational and Container Components from 2015.
His update from 2019:
Update from 2019: I wrote this article a long time ago and my views
have since evolved. In particular, I don’t suggest splitting your
components like this anymore. If you find it natural in your codebase,
this pattern can be handy. But I’ve seen it enforced without any
necessity and with almost dogmatic fervor far too many times. The main
reason I found it useful was because it let me separate complex
stateful logic from other aspects of the component. Hooks let me do
the same thing without an arbitrary division. This text is left intact
for historical reasons but don’t take it too seriously.
With the advent of React hooks the distinction between "smart" and "dumb" components, and "container" and "presentational" components, was all but eliminated.
The common pattern and "best practice" now is to write React Function components and just use the React hooks. In the case of using Redux and React-Redux, the useDispatch and useSelector hooks instead of the connect Higher Order Component. I've not gone out of my way to write a React Class component or split my code between "presentation" and "container" since the advent of React hooks.
My rule of thumb is to do it all in one component. Then as you create more and more components you'll see patterns start to emerge. So instead of copying and pasting code from component to component you can make a presentational component that takes in props for what to render. Some of those props can even be what to do when a button is clicked or a box is checked.
Overall your presentational components will end up resembling something like one of the various react js ui frameworks out there such as https://mui.com/

Rendering query string variables in React [duplicate]

After spending some time learning React I understand the difference between the two main paradigms of creating components.
My question is when should I use which one and why? What are the benefits/tradeoffs of one over the other?
ES6 classes:
import React, { Component } from 'react';
export class MyComponent extends Component {
render() {
return (
<div></div>
);
}
}
Functional:
const MyComponent = (props) => {
return (
<div></div>
);
}
I’m thinking functional whenever there is no state to be manipulated by that component, but is that it?
I’m guessing if I use any life cycle methods, it might be best to go with a class based component.
New Answer: Much of the below was true, until the introduction of React Hooks.
componentDidUpdate can be replicated with useEffect(fn), where fn is the function to run upon rerendering.
componentDidMount methods can be replicated with useEffect(fn, []), where fn is the function to run upon rerendering, and [] is an array of objects for which the component will rerender, if and only if at least one has changed value since the previous render. As there are none, useEffect() runs once, on first mount.
state can be replicated with useState(), whose return value can be destructured to a reference of the state and a function that can set the state (i.e., const [state, setState] = useState(initState)). An example might explain this more clearly:
const Counter = () => {
const [count, setCount] = useState(0)
const increment = () => {
setCount(count + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
</div>
)
}
default export Counter
As a small aside, I have heard a number of people discussing not using functional components for the performance reasons, specifically that
"Event handling functions are redefined per render in functional components"
Whilst true, please consider if your components are really rendering at such a speed or volume that this would be worth concern.
If they are, you can prevent redefining functions using useCallback and useMemo hooks. However, bear in mind that this may make your code (microscopically) worse in performance.
But honestly, I have never heard of redefining functions being a bottleneck in React apps. Premature optimisations are the root of all evil - worry about this when it's a problem.
Old Answer: You have the right idea. Go with functional if your component doesn't do much more than take in some props and render. You can think of these as pure functions because they will always render and behave the same, given the same props. Also, they don't care about lifecycle methods or have their own internal state.
Because they're lightweight, writing these simple components as functional components is pretty standard.
If your components need more functionality, like keeping state, use classes instead.
More info: https://facebook.github.io/react/docs/reusable-components.html#es6-classes
UPDATE Jan 2023
TLDR; Functions are the best way to create components. React.Component is a legacy API.
"We recommend to define components as functions instead of classes."
"Class components are still supported by React, but we don’t recommend using them in new code."
https://beta.reactjs.org/reference/react/Component
UPDATE March 2019
Building on what was stated in my original answer:
Are there any fundamental differences between React functions and
classes at all? Of course, there are — in the mental model.
https://overreacted.io/how-are-function-components-different-from-classes/
UPDATE Feb 2019:
With the introduction of React hooks, it seems as though the React teams wants us to use functional components whenever possible (which better follows JavaScript's functional nature).
Their motivation:
It’s hard to reuse stateful logic between components.
Complex components become hard to understand.
Classes confuse both people and machines.
A functional component with hooks can do almost everything a class component can do, without any of the draw backs mentions above.
I recommend using them as soon as you are able.
Original Answer
Functional components aren't any more lightweight than class based components, "they perform exactly as classes." - https://github.com/facebook/react/issues/5677#issuecomment-241190513
The above link is a little dated, but React 16.7.0's documentation says
that functional and class components:
are equivalent from React’s point of view
https://reactjs.org/docs/components-and-props.html#stateless-functions
There is essentially no difference between a functional component and a class component that just implements the render method, other than the syntax.
In the future (quoting the above link):
we [React] might add such optimizations
If you're trying to boost performance by eliminating unnecessary renders, both approaches provide support. memo for functional components and PureComponent for classes.
https://reactjs.org/docs/react-api.html#reactmemo
https://reactjs.org/docs/react-api.html#reactpurecomponent
It's really up to you. If you want less boilerplate, go functional. If you love functional programming and don't like classes, go functional. If you want consistency between all components in your codebase, go with classes. If you're tired of refactoring from functional to class based components when you need something like state, go with classes.
Always try to use stateless functions (functional components) whenever possible. There are scenarios where you'll need to use a regular React class:
The component needs to maintain state
The component is re-rendering too much and you need to control that via shouldComponentUpdate
You need a container component
UPDATE
There's now a React class called PureComponent that you can extend (instead of Component) which implements its own shouldComponentUpdate that takes care of shallow props comparison for you. Read more
As of React 17 the term Stateless Functional components is misleading and should be avoided (React.SFC deprecated, Dan Abramov on React.SFC), they can have a state, they can have hooks (that act as the lifecycle methods) as well, they more or less overlap with class components
Class based components
state
lifecycle methods
memoization with React.PureComponent
Functional components:
state (useState, useReducer hooks)
lifecycle methods (via the useEffect, useLayoutEffect hooks)
memoization via the memo HOC
Why i prefer Funtional components
React provide the useEffect hook which is a very clear and concise way to combine the componentDidMount, componentDidUpdate and componentWillUnmount lifecycle methods
With hooks you can extract logic that can be easily shared across components and testable
less confusion about the scoping
React motivation on why using hooks (i.e. functional components).
I have used functional components for heavily used application which is in production. There is only one time I used class components for "Error Boundaries" because there is no alternative "Error Boundaries" in functional components.
I used "class component" literally only one time.
Forms are easier with functional, because you can reuse form input fields and you can break them apart with React display conditionals.
Classes are one big component that can't be broken down or reused. They are better for function-heavy components, like a component that performs an algorithm in a pop-up module or something.
Best practice is reusability with functional components and then use small functional components to assemble complete sections, ex.- form input fields imported into a file for a React form.
Another best practice is to not nest components in the process of doing this.
Class-based components offer a more structured and organized way to define and implement a component, and they provide additional features and capabilities, such as the ability to use local state and lifecycle methods. This can make them a good choice for creating complex components that require a lot of logic and functionality.
On the other hand, functional components are simpler and easier to work with, and they can be more performant because they are more lightweight. They are also easier to test and debug, because they are pure functions that don't have side effects. This makes them a good choice for creating simple components that don't require a lot of logic or state management.

Understanding the props concept in React

While I'm learning React, it's always said that you should keep your state in the parent component and pass them as props to its children.
But in the real world, whenever I start building a react app, I end up passing data from a child component to its parent.
For example, if I have to implement a form somewhere in my react app, I create an extra component for it (for example, FormComponent) and import it in my App component.
But now, I have to pass the form data form the FormComponent to the App component. In other words, from the child component (FormComponent) to the parent (App component).
And this was just an example. Usually, I always end up in situations where I have to pass data from child to parent rather than the other way around.
Do I misunderstand the concept of passing props completely?
If we stay with the above example, is my approach, right?
You can't pass data from child to parent as in React, The Data Flows Down.
So usually you pass callbacks from parent to its children, but the state remains in the parent.
This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.
If you in a situation where the code becomes unreadable, unmaintainable, you should consider Lifting the State Up.
Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor.
Aside from it, a common anti-pattern is Prop Drilling, Context API, and many state libraries like Redux, MobX, and Recoil trying to solve such problems with some extra features.
1- In your case you can pass a function ( Example: handleSubmit() ) through props from parent to child.
And so when this function is called the child's data would be hundled from the parent.
you can use this doc page to inspire your code.
2- Otherwise you can use react redux, and then you can hundle all data at any component in your project using one global state called redux store.
want to learn more about react redux click here.
3- Have a nice day ^_^ .

[React]Container Component design

I have 3 components in a html page.
A,B,C
By the PSD desgin ,in the DOM level , A includes B and B includes C.
so in the React level , I'd like to design component tree as follow:
A(stateful component) ->B (stateless component) ->C (stateless component)
I will make A redux-aware by connect method and hand down the redux state to B then -> C.
However many guides recommend that a stateful component can only contain stateless components whereas there's no mentioned whether:
1. a stateless component can contain another stateless component?
2. a stateless component can contain another stateful component?
3. a stateful component can contain another stateful compoent?
so anyway ,how to design my components, thanks in advance!!
A(stateful component) ->B (stateless component) ->C (stateless component)
both B and C expect the state from A to pass down to them.**
Some times you can learn more my reading example code, take a look at this example Todo List provided by redux it clearly shows that MainSection contains TodoItem and a Footer both of which are stateful and MainSection itself is stateful. A major example may even be the Material-UI library which is all stateful components and you can use it with stateless or stateful components.
There is no reason stateless components can't contain state-less components and there is no reason stateless components can't contain stateful components. An example of a stateless component containing stateful components is literally your top level App or index file at times. If the repo linked above, take a look at App.js.
The main concern with stateful components containing stateful components is a lot of needless updates to your UI. These are some times not obvious because the shadow DOM diff's against the DOM and makes the appropriate changes, but there is non-the-less a cost to the diff and the operation is triggered every time your state changes.
A good way to solve this issue is to keep your components fairly flat in their dept or to implement the shouldComponentUpdate function as needed.
Having state in your components just makes things easier to manage due to separation of concerns, so I find it hard to believe using them under stateful or stateless components could be an issue. Stateless components will render every time the component that contains them renders, so perhaps the issue of embedding stateless components inside stateless components is one of depth, i.e. the deeper your DOM the more complex the diff operations (purely guessing based on experience) so the guideline discourage this so that you can keep your tree as flat as possible.
Honestly, I don't see any of this being a problem as long as you use good coding practices and are aware of the consequences of your decisions.

ReactJS: what is the difference between functional component and class component

Could anyone can explain in detail the difference between functional component and class component in ReactJS?
When we use a functional component and when we use the class component?
Here's a great article, "Presentational and Container Components", by Dan Abramov that can help you with that.
And here's a tl;dr; of the way I understand this:
You'll have to use class CreatePostForm extends Component {} or React.createClass() if:
you need access to your component's lifecycle methods (ie.: componentWillMount or componentDidMount) – NOTE: Since React 16.8, this is no longer necessarily true and I would highly recommend reading on React Hooks as they can make things simpler once you get comfortable with them;
your component have direct access to your store and thus holds state (some people also call these components: smart components or containers).
When your component just receive props and render them to the page, then you have a 'stateless component' (some people call these components dumb components or presentational components) and can use a pure function to represent it and it can be as simple as this
import React from 'react';
export default () => <p>Hello from React!</p>;
Now, it's important to remember that a pure function can get way more complex than this and if you're comfortable with some ESNext syntax and destructuring and spreading attributes, you can have a presentational component that looks like this:
import React from 'react';
import AnotherComponent from './AnotherComponent';
export default ({ children, ...rest }) =>
<AnotherComponent extraProp="anExtraProp" { ...rest }>
{ children }
</AnotherComponent>;
Hope this helps.
See this picture. I am too much late but i will help the others.
Source of Image is Udemy Course
Functional Stateless Components (that middle word you missed is the important one) are just a 'dumb' function that takes props as an input and outputs markup. They don't have any state or methods or anything like that. Just (props) => { return <span>props.foo</span>; }
Class components can have state, variables, methods etc.
Functional Components:
These components are stateless components and does not have react life-cycle methods.
These components can be used for presentation purpose.
These components can be easy to debug,test.
Class Components:
These components are statefull components and can support react life-cycle methods by extending react components.
These components can be used when you want to create methods , state for an component.
Functional Components
A functional component is basically a JavaScript function which returns a React element. Its accepts props as argument and returns valid JSX
Class Components
Class Components are more complex than functional components including constructors, life-cycle methods, render( ) function and state (data) management. Class components are ES6 classes.
Benefits of using Functional Components
Functional components are easy to test.
It can have better performance.
Functional components are easy to debug.
It end up with less code.
It help you to use best practices.
Functional components can reduce coupling.
For more click here
When react was introduced, only class components were used to re-render the component when state changes and functional components were treated as presentational components as they don't have state access.
From react 16.8 version update, with introduction to hooks, now functional components also have state access.
In the class component, managing state is performed in a single state object but in function we can create as many hooks as we want.
In the class component, when re-render happens, it will invoke methods but in functional components when state update, it re-create and invoke inner functions if we don't use useCallback and useMemo hooks.
Only Class components are used as Error Boundaries
Functional Component : Using simple javascript function to define component.
it uses props as input(stateless)
Class Component : Using class to define a component(state Component)
Besides the obvious difference in the syntax, you need use a class component instead of a function component when your component needs to store and manipulate its own internal state or when you need access to the several lifecycle methods like componentDidMount, etc to perform network operations, manipulate the DOM, interact with third-party libraries, etc
I recommend you to take a look a the React docs (https://reactjs.org/docs/react-component.html) about the React.Component API to find a detailed description of all the lifecycle methods and the state API.
1-Functional component are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks
2-You end up with less code
3-They help you to use best practices. It will get easier to separate container and presentational components because you need to think more about your component’s state if you don’t have access to setState() in your component
4-The React team mentioned that there may be a performance boost for functional component in future React versions
In the world of react, there are two ways to write components:-
Using functions
Using class
The following example shows the two ways you can write the same component.
Functional component
import React from "react";
function FunctionalComponent() {
return <h1>Hello, world</h1>;
}
Class component
import React, { Component } from "react";
class ClassComponent extends Component {
render() {
return <h1>Hello, world</h1>;
}
}
With Recent releases of React, the choice of when to write when depends on the developer's preferences.
Both styles have their own pros and cons. Functional components are taking over modern React in the foreseeable future. Everything we can do with class components is possible with the functional components. It can be written shorter and simpler, which makes it easier to develop, understand, and test.
React team is supporting more React hooks for functional components that replace or even improve upon class components. They mentioned in prior releases that they will make performance optimizations in functional components by avoiding unnecessary checks and memory allocations. And as promising as it sounds, new hooks are recently introduced for functional components such as useState or useEffect while also promising that they are not going to obsolete class components but recommend a gradual adoption strategy.
Function component is a Hook Using work and the usestate and any other hook function to use and dynamic data display then some problem for function component in a reactjs
Class Component is an easy way to use for compare to function component and daynamic data update then to easily work. Class component is what state and props use to pass runtime data to a component.

Categories

Resources