We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Refactoring Class Components to Functional Components

00:00

Formal Metadata

Title
Refactoring Class Components to Functional Components
Title of Series
Number of Parts
36
Author
Contributors
N. N.
License
CC Attribution 3.0 Germany:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal purpose as long as the work is attributed to the author in the manner specified by the author or licensor.
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
The React development landscape is always changing. "Refactoring Class Components to Functional Components" is a talk about transforming code from class components to functional components. We'll explore why this change is important and the advantages of functional components, including improved readability, reusability, and performance optimization.
Interactive televisionFunctional programmingCodeSoftware developerProjective planeOnline helpProcess (computing)Goodness of fitComputer animationLecture/Conference
GoogolFunctional programmingCode refactoringDisintegrationData conversionClient (computing)Plane (geometry)Process (computing)MathematicsLibrary (computing)CodeShared memoryBitLogicThermal expansionState of matter1 (number)Functional programmingData conversionDifferent (Kate Ryan album)Client (computing)Interface (computing)Mathematical optimizationOrder (biology)Front and back endsSoftware developerHookingComputer animationLecture/Conference
Inheritance (object-oriented programming)Level (video gaming)VolumenvisualisierungFunctional programmingImplementationoutputState of matterPhysical systemElement (mathematics)Data managementPhase transitionLibrary (computing)Video gameCycle (graph theory)Software developerHookingCodeFlow separationSound effectAdditionType theoryLecture/ConferenceXMLComputer animation
Phase transitionState of matterSound effectHookingConstructor (object-oriented programming)Object (grammar)InformationoutputLogicFunction (mathematics)Price indexProxy serverVolumenvisualisierungInheritance (object-oriented programming)Formal grammarForm (programming)Mathematical optimizationDefault (computer science)Artistic renderingGroup actionGroup actionState of matterFunctional programmingHookingData storage devicePhase transitionVolumenvisualisierungArray data structureCycle (graph theory)Multiplication signSound effectVideo gameForcing (mathematics)Line (geometry)Flow separationNumberObject (grammar)Default (computer science)Level (video gaming)Connected spaceConstructor (object-oriented programming)Category of beingNetwork topologyRevision controlMathematical optimizationMathematicsLogicInstance (computer science)Extension (kinesiology)Exterior algebraDifferent (Kate Ryan album)Declarative programmingBridging (networking)Element (mathematics)Parameter (computer programming)Reduction of orderRoutingConfidence intervalAssociative propertyCodeLecture/ConferenceXMLComputer animation
Function (mathematics)Parameter (computer programming)Group actionSoftware testingData storage deviceSoftware testingMultiplication signMereologyProjective planeConnected spaceLevel (video gaming)Router (computing)HookingLibrary (computing)CASE <Informatik>Patch (Unix)Intrusion detection systemOperator (mathematics)MathematicsState of matterSubsetGroup actionFunctional programmingResultantParameter (computer programming)Cartesian coordinate systemBefehlsprozessorWeb 2.0Software frameworkWeb browserUnit testingPhase transitionEqualiser (mathematics)Pairwise comparisonObject (grammar)Game controllerOnline helpRange (statistics)Visualization (computer graphics)IntegerVolumenvisualisierungDependent and independent variablesExecution unitCausalityDivisorComputer animationLecture/Conference
Musical ensembleComputer animationLecture/Conference
1 (number)Computer animationLecture/Conference
Plane (geometry)Multiplication sign1 (number)Content (media)Presentation of a groupMusical ensembleStudent's t-testUbiquitous computingPerspective (visual)Process (computing)CodeSoftwareInstance (computer science)Point (geometry)Inheritance (object-oriented programming)TelecommunicationCloningSound effectGoodness of fitSummierbarkeitComputer animationLecture/Conference
Transcript: English(auto-generated)
Thank you. So hello, good morning, everyone. I'm Tisha Soumya. And I recently graduated and started working as a first time developer. It's been two months at Dell Technologies.
So I participated in Google Summer of Code 2023 and submitted my proposal for refactoring React class components to functional components and got the opportunity to work on this. It was quite an exciting experience. So my mentors for Google Summer of Code
were Victor, Nilesh, and Jefferson. I want to thank them all for helping and guiding me throughout this project. And especially, I want to thank Nilesh. He has been of immense help. And this was my first international travel. So he has been of helpful in every process and everything.
So thank you. So why is refactoring important to functional components? First would be ecosystem alignment. The React ecosystem is increasingly
moving towards functional components. And hooks are the preferred way of doing things. And the alignment means that most of the libraries and tools and best practices are developed around functional components. So keeping the code base is very important. Up to date is very important.
Another would be having one means for developing. The contributors to Plone would not have to work both on class components and functional components. So it would be good to have only one means for the developing process. Hooks are the only way nowadays of using the only way of some of the libraries in React.
And this would allow us to keep up to date through most recently used innovations and technology. And the conversion will make it easier to integrate the new Plone client, which has been developed, as that it is intended to be in hooks only. And also, it helps with reuse of logic.
The custom hooks can be created to encapsulate and share logic across different components and improve performance optimization. The state hooks enables to use React Memo, higher order components, or the use of useMemo and useCallback, which are developed to optimize rendering performances.
So what are React Memos? We start with the basics. In the backend world, we have the solid principles. And one of those principles is open-close principle. This states that the interfaces are open for expansion but closed for modification.
Simply put, don't change interfaces. Just create new ones. Similarly, React components are independent and reusable bits of code and serve the same purpose as JavaScript functions but work in isolation and return HTML. They're no longer bound by implementation of other components.
So this creates the flexibility of using the latest innovations and also using any JavaScript library and components which can be installed as an NPM package. So components come in two types, class components and functional components. So yeah, class components.
So React class components have been a cornerstone of React development for many years. And they are defined as ES6 classes and extend the React component class. To track the state of the components and use life cycle methods, we have to use the components,
we have to use the class components in React. And they're still supported by React but the React team now recommends using functional components in new code. Moving on to the functional components. So they're introduced in 60 React system .8 with hooks that have gained significant popularity
due to the simplicity and improved performances. They're just JavaScript functions that accept props as input and return JSX elements. And React hooks such as useState, useEffect allow functional components to manage state and handle side effects. So functional components are now essentially identical
to class components thanks to the addition of hooks. The life cycle of the components, there are basically three phases in the life cycle of a component, mounting, updating and unmounting. Mounting is the first stage where the component is first created and inserted into the DOM.
During this phase, several life cycle methods are invoked by React which enables the developer to configure the components. Updating, so this phase occurs when the component props or state changes
and the component needs to be updated into the DOM. Unmounting, this is the final phase of the life cycle and this removes the component and its associated resources from the DOM tree itself. Hooks, so the life cycle methods that we saw earlier
are technically particular to class-based components and not intended for functional components. However, since the concept of hooks was released in React, we now use the abstracted version of these life cycle methods when we are working with functional component states. And React hooks are functions which allow us
to hook into a React state and the life cycle features within functional components. So effect hook, so like we saw, like useEffect is mostly, can be thought of as a collation out of three separate life cycle methods,
but it can be more useful to think it off simply as a way to run side effects after render, including the potential cleanup you do want to do before each one and before unmounting. If you want to prevent the useEffect to run
on every render, we can make use of the dependencies arrays. So after effect, after the life cycle and effect hooks, the state of the components. So React components has built-in state objects. The state object is where you store the property values
that belong to the component. When the state object changes, the component re-renders. They're initialized in the constructor and it can contain as many properties as needed. State objects can be referred from anywhere in the component using this top property name syntax.
State hooks. So this is how state is managed in functional components. So the major difference between hooks and a class-based state are that hooks are used in symmetrical components. So, and the problem with class state is it is deep nested and deep nested components
and the use of this keyword in state declaration and modifications. So beside new state, we can see useReducer, which can be a preferred way of using state when there is a complex logic like when state values depends on previous states.
So in, for ref, how is ref used in both class components and functional components? So first, what is ref? React team has made refs as which act as a bridge. And this bridge allows a component to access or modify an element that the ref is attached to.
The ref provides us a way to bypass the updates and re-renders. This is very useful, but we should not use ref as an alternative to props or state changes, or states. So to create ref in class-based components, we use react.createRef method.
And refs are set to an instance property so that they can be used as a reference throughout the component. And ref in hooks. So here, useRef is a hook that uses the same ref throughout. It saves the value between re-renders. And unlike createRef, it does not create new instances
for the ref for every render. So going on to the performance, how performance is optimized. So in react class components, we can either extend pure components or use should component update. So you should component update is invoked
before rendering when new props on state are being received. This defaults it through. And this method is not called for initial render or when force update is being used. This method only exists as a performance optimization. And if should component update returns false,
then the update lifecycle methods are not invoked. So performance optimization in functional components. For performance optimization, we can use, we use useMemo and useCallbacks are the tools built to help us.
And they do this in two ways, either reducing the amount of lines of code, like amount of work that will be done on every render, or reducing the number of times the component needs to re-render. So what is useMemo? UseMemo is like a little cage. And it re-computes the value
every time there's a change in a dependency array. So a useCallback is the exact same thing, but for functions instead of arrays or objects. And similar to arrays and objects, functions are compared by references and not by value.
Redux, Redux hooks. So React Redux includes its own custom hook APIs which allow your React components to subscribe to the Redux store and dispatch actions. So how React Redux, like we used in last components, like connect function.
So connect function connects a React component to Redux store. It provides its connected component with the pieces of data that is needed by the component from the store. And the function it can use, sorry, the function it can use to dispatch actions to the store.
In the file, connect has two arguments, map state to props and map dispatch to props. So, which deals with state of the store, state and the dispatch, respectively. Map state to props.
As the first argument passed in the connect, map state to props is used for selecting the part of data from the store and from the store that the connected component needs. It's frequently, sorry, it is called every time the store changes, like when the store state changes,
all the map state to props functions are invoked again. So if map state to, this function is slow, then it can be a bottleneck to the application. Use selector. So use selector is equivalent to what we saw the map state to props, and that takes an argument
that returns the part of the state that the component needs. So use selector will also cause component re-render after redox action was dispatched, only if the result will be different than the last one. It checks whether it has changed using the strict equality comparison of the result.
And if your selected result is trapped in an object, then hook will cause a component to re-render every time an action is dispatched. And the solution for this problem is to introduce shallow comparison of the result object.
And this is how we can use it. Map dispatch to props. As a second argument to connect, map dispatch to prop is used for dispatching actions to the store. And dispatch is a function of the redox store. You can call store.dispatch to dispatch an action.
Use dispatch, and this is an equivalent to the earlier function. We will invoke use dispatch and store it to a variable, and dispatch will work with actions imported from the actions folder. And the hooks is used to update the state
of the component and return the new state. In the custom hooks, and react-intel react-fouter. We can use, make use of custom hooks and other hooks, like from other packages, JavaScript libraries.
Using these hooks, we have to keep in mind the use cases and the trade-offs that are included here. Testing, so testing was indirectly the most important part of the project because there was no room for breaking changes over here. So I tested it, after refactoring the components,
they have been tested, they were tested with Cypress, Jorogorg, and JestTest. And also, I wrote some of the, I wrote CypressTest, and so we put tests for the components for which they were not available. And the ways of testing would, ways of testing BOLT support, BOLT has acceptance testing,
which is done using Cypress, Jest, which is a standard defacto node.js test runner. Unit testing, which is achieved using Jest as a test runner. And storybook test, BOLT provides the integration with storybook, which is used to document,
visualize, and demonstrate various UI components in isolation. Storybook test. So the, I'm sorry, what does storybook test? It is basically visual documentation, have some visual documentation. Storybook serves as visual documentation
for UI components, and also has isolated component testing. And story, it has also many add-ons. It supports a wide range of add-ons that enhances testing capabilities, like control add-ons, gives you the graphical UI to interact with the component, arguments dynamically without needing to code.
And there are many other add-ons that have visual testing, responsiveness testing, and even automated testing tools, like Cypress. So I would like to show one of the examples of how storybook tests are, like,
let me open, it's not visible, okay. Never mind, I will show you after this. Cypress test. So what are Cypress tests? They are basically a typical end-to-end testing.
Test visits the application in the browser and performs actions via the UI, just like a real user would. So, like, while component testing, Cypress mounts the components from a supported web framework and executes a component test. And we can use the DOM, we use it basically like the DOM,
we refer it using the class or the names or IDs in the test, and it goes and clicks on it, or whatever the actions are provided over there, operations that we define in the test. So yeah, this is my update till now for the project.
Like, 29 PRs have been merged, which includes the factored components, Cypress and storybook tests, for which, for those which are not present, 29 PRs are still open, and components which, a lot of components are getting refactored,
and which I think will be working next. So I hope you'll take it, thank you. Thank you, Tisha, for showing your work. Any questions?
Tisha, I was wondering who is delaying the merging of the remaining PRs? I guess I meant us.
First of all, thanks, Tisha, for your amazing work, and yeah, I'm really looking forward for merging the remaining ones. Yeah, but there are an insane amount of work that she did, and yeah, I very appreciate it,
and she did it in a very professional way. So yeah, thanks, Tisha, again. Thank you. And we couldn't merge everything for 17, but there will be merge for 18, so that's where we'll continue looking forward for merge, continue the final merge in the PR.
And thank you, because thanks to you, and of course, Victor, pointing me to your code, it saved me hours of work, because I wanted to implement something in the new way, and every single time I looked into Voto code, it was class-based, and I was like, I don't know.
So thank you. Thank you. In fact, it will be a good idea, so maybe tomorrow it's not, or we won't have time to, but I heard about a lot of people, what are the best practices, the ones that you already showed today,
that maybe we need to also get the content of your presentation, put it in a document, in the documentation, how to convert a class-based component to a functional one in an effective way, an easy way, and what are the culprits, and all, yeah. I think it will be a good idea.
Thanks. Thank you so much. Yeah, thank you, Tisha, for your great presentation and your work. I know how important that is to refactor things in the code base when I look back. When I tried to learn like, so three, and Grok, they had two ways,
or three ways of doing the same thing, and as a newbie that confused the hell out of me, that you have different ways, so this is really important work that you did, and you did it in a fantastic way, so thanks a lot for that. Being a Google Summer Code student myself, I started also my career in the Plone community.
I would like to ask you if there's anything that comes to mind that the Plone community could do better to onboard new members that come into the Plone community in the future. Like, it's a tough question. Like, mostly it is an easy, like it's easy for me,
like it was easy, not difficult for me to come here and interact with you guys. You guys are really very helpful, and I communicated, so it was easy, but besides this, no, like on software, if I would say, like it's the only thing I face in difficulty is installation of the whole thing.
That's the main thing, and besides that, community-wise, it's very easy. It was very easy for me. I did not hesitate, like, to talk to you. I think it was easy for you because I heard that your proposal, your Google Summer Code student proposal was outstanding, so I guess that might have helped, and regarding the installation,
we all know that this is painful, and we would be incredibly thankful if you could like maybe give us recommendation there how we could improve things, we could work on this together, for instance, but it's hard, it's super easy if you're a newbie to tell where things are hard to understand, but for people that are long in the long community,
it's really hard, and this is something that I also personally only understood at a later point that when I was a Google Summer Code student myself, and a newbie, I could have contributed so much more because my perspective was way, it was way easier for me as a newbie
to contribute and say what we could improve than people that are long in the long community. Any more? Tisha, has any Volto company offered you a job yet?
No. Okay. Thank you, Tisha, for your presentation and your work. Big applause for her.
Thank you so much, everyone. Thank you.