I learn react, and I dont understand what is the difference between placing data or function inside or outside function components ?
What is the best practice, and when use the first or second example ?
Declare in component :
import React from 'react'
const SomeComponent = () => {
const list = ['foo', 'bar']
function add(foo) {
return foo + 1
}
// other logics...
return (
// list...
)
}
Declare outside the component :
import React from 'react'
const list = ['foo', 'bar']
function add(foo) {
return foo + 1
}
const SomeComponent = () => {
// other logics...
return (
// list...
)
}
Have a nice day :)
If your function is a pure function that is not accessing the component's context, you can just put it outside of the component.
It doesn't matter in that case.
But when you need to use this inside the function, it's necessary to define it inside the component.
This post could be helpful too.
Functions in stateless components?
I think the 2nd option is a better cause when react re-renders the "SomeComponent", it doesn't have to create foo() again and again.
If you don't want to use class components like state and other methods than declare outside component else inside the component. In inside component call function as this.functionName
Related
I have an android app which calls the a function present inside the head of my react
page. All i want is to allow the the function to set a state inside the react component
<head>
<script>
webViewAndriodInteraction(parm1)
{
//Here i want this function to change the state of my react functional component
//setSomeState(pram)
}
</script>
</head>;
function LiveScreen(props) {
const [somedata, setSomeState] = useState();
return <h1>someData</h1>;
}
It's probably against some React best practices, but you could do this:
In your component, define an effect that puts your state setter on the window object:
useEffect(() => {
window.setSomeState = setSomeState;
return () => {
window.setSomeState = undefined;
};
}, []);
And in your webViewAndriodInteraction function:
if (window.setSomeState !== undefined) {
// call window.setSomeState here
}
You also need to ensure that your call to window.setSomeState is deferred until the function gets defined. So if you're sure it's going to get defined, you could set a timeout or retry the if check a few times with a given delay.
I was playing with ReacJS. I noticed a thing-
In case of Class Component during re-rendering class variable's updated value is updated in screen like:
import React, { Component } from "react";
class Temp extends Component {
constructor(props) {
super(props);
this.count = 0;
this.state = {
foo: 0,
};
}
render() {
return (
<button
onClick={() => {
this.setState({ foo: this.state.foo + 1 });
this.count++;
}}
>
{this.count} - {this.state.foo}
</button>
);
}
}
export default Temp;
But in case of function component the updated value of the ordinary variable is not updated in the screen during re-rendering.
import React, { useRef, useState } from "react";
const RefComponent = () => {
const [stateNumber, setStateNumber] = useState(0);
let refVar = 0;
function incrementAndDelayedLogging() {
setStateNumber(stateNumber + 1);
refVar++;
}
return (
<div>
<button onClick={incrementAndDelayedLogging}>Click</button>
<h4>state: {stateNumber}</h4>
<h4>refVar: {refVar}</h4>
</div>
);
};
export default RefComponent;
Is this how React was implemented or I'm messing around something? I'm curious to know about it.
Thanks
Functional components in React don't have instances, so things like class or instance variables don't necessarily make sense; like others have pointed out in the comments here, React will render (call) functional components and "reset" any local variables that are not explicitly state. Behavior like instance variables for functional components are achieved with useRef.
From the docs:
The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.
This is a consequence of functional components.
Think about it like this: Each time a state var is updated or a prop is updated your function gets called again. All variable declaration will happen again (states are a special case), so let refVar = 0; gets called again.
If you need that variable to live for multiple renders you'll need to declare it in a context that survives re-renders.
You have at least 2 ways of achieving this
declare a state for it with useState
declare it at the module level, but know all your instances of RefComponent will share the same instance
I am trying to write a function that handles a button click.
I want things to happen:
The function gets a string and changes the state named "chosenGenre" to the given string.
When a certain button is clicked, it calls the function and returns a string.
The string/state "chosenGenre" is saved so I can use it later in another component.
This is what I have wrote but I think the way I deliver the string after the button is clicked isn't right.
import React, { Component } from 'react';
import Genre from './Genre';
import './GenreSelectPage.css';
import Blues from '../Blues.png';
import Classical from '../Classical.png';
import Country from '../Country.png';
export default class GenreSelectPage extends Component{
state = {
chosenGenre: ""
}
handleClick = (genreName) => {
this.setState({chosenGenre: genreName});
}
render(){
return(
<div className = "GenreSelectPage">
<h3>Select your desired Kollab Room Genre</h3>
<Genre genrePicture= {Blues} genreClicked = {this.handleClick("blues")}/>
<Genre genrePicture= {Classical} genreClicked = {this.handleClick("Classical")}/>
<Genre genrePicture= {Country} genreClicked = {this.handleClick("Country")}/>
)
}
}
What should I change in order to call the function in the right way and keep the result?
the problem is this.handleClick("blues") is executed during render, it returns undefined, similar to genreClicked={undefined}, with a side effect to schedule 3 asynchronous setStates...
you can use a factory function that returns an event handler function with access to a closure variable:
makeHandleClick = (genreName) => (event) => {
this.setState({ chosenGenre: genreName });
// console.assert(this.state.chosenGenre); // FYI: not possible, setState is async
}
render() {
...<Genre genrePicture={Blues} genreClicked={this.makeHandleClick("blues")} />
I'm trying to convert this cool <canvas> animation I found here into a React reusable component. It looks like this component would require one parent component for the canvas, and many children components for the function Ball().
It would probably be better for performance reasons to make the Balls into stateless components as there will be many of them. I'm not as familiar with making stateless components and wondered where I should define the this.update() and this.draw functions defined in function Ball().
Do functions for stateless components go inside the component or outside? In other words, which of the following is better?
1:
const Ball = (props) => {
const update = () => {
...
}
const draw = () => {
...
}
return (
...
);
}
2:
function update() {
...
}
function draw() {
...
}
const Ball = (props) => {
return (
...
);
}
What are the pros and cons of each and is one of them better for specific use cases such as mine?
The first thing to note is that stateless functional components cannot have methods: You shouldn't count on calling update or draw on a rendered Ball if it is a stateless functional component.
In most cases you should declare the functions outside the component function so you declare them only once and always reuse the same reference. When you declare the function inside, every time the component is rendered the function will be defined again.
There are cases in which you will need to define a function inside the component to, for example, assign it as an event handler that behaves differently based on the properties of the component. But still you could define the function outside Ball and bind it with the properties, making the code much cleaner and making the update or draw functions reusable:
// you can use update somewhere else
const update = (propX, a, b) => { ... };
const Ball = props => (
<Something onClick={update.bind(null, props.x)} />
);
If you're using hooks, you can use useCallback to ensure the function is only redefined when any of its dependencies change (props.x in this case):
const Ball = props => {
const onClick = useCallback((a, b) => {
// do something with a, b and props.x
}, [props.x]);
return (
<Something onClick={onClick} />
);
}
This is the wrong way:
const Ball = props => {
function update(a, b) {
// props.x is visible here
}
return (
<Something onClick={update} />
);
}
When using useCallback, defining the update function in the useCallback hook itself or outside the component becomes a design decision more than anything: You should take into account if you're going to reuse update and/or if you need to access the scope of the component's closure to, for example, read/write to the state. Personally I choose to define it inside the component by default and make it reusable only if the need arises, to prevent over-engineering from the start. On top of that, reusing application logic is better done with more specific hooks, leaving components for presentational purposes. Defining the function outside the component while using hooks really depends on the grade of decoupling from React you want for your application logic.
Another common discussion about useCallback is whether to always use it for every function or not. That is, treat is as opt-in or always recommendable. I would argue to always use useCallback: I've seen many bugs caused by not wrapping a function in useCallback and not a single scenario where doing so affects the performance or logic in any way. In most cases, you want to keep a reference while the dependencies don't change, so you can use the function itself as a dependency for other effects, memos or callback. In many cases the callback will be passed as a prop to other elements, and if you memoized it with useCallback you won't change the props (thus re-render) other components independently of how cheap or costly that would be. I've seen many thousands of functions declared in components and not a single case in which using useCallback would have any down side. On the other hand most functions not memoized with useCallback would eventually be changed to do so, causing serious bugs or performance issues if the developer doesn't recognize the implications of not doing so. Technically there is a performance hit by using useCallback, as you would be creating and additional function but it is negligible compared to the re-declaration of the function that always has to happen either you use useCallback or not and the overall footprint of React and JavaScript. So, if you are really concerned about the performance impact of useCallback versus not using it, you should be questioning yourself if React is the right tool for the job.
You can place functions inside stateless functional components:
function Action() {
function handlePick(){
alert("test");
}
return (
<div>
<input type="button" onClick={handlePick} value="What you want to do ?" />
</div>
)
}
But it's not a good practice as the function handlePick() will be defined every time the component is rendered.
It would be better to define the function outside the component:
function handlePick(){
alert("test");
}
function Action() {
return (
<div>
<input type="button" onClick={handlePick} value="What you want to do ?" />
</div>
)
}
If you want to use props or state of component in function, that should be defined in component with useCallback.
function Component(props){
const onClick=useCallback(()=>{
// Do some things with props or state
},[])
return <Something {...{onClick}} />
}
On the other hand, if you don't want to use props or state in function, define that outside of component.
const computeSomethings=()=>{
// Do some things with params or side effects
}
function Component(props){
return <Something onClick={computeSomethings} />
}
For HTML tags you don't need useCallback because that will handle in react side and will not be assigned to HTML
function Component(props){
const onClick=()=>{
// Do some things with props or state
}
return <div {...{onClick}} />
}
Edit: Functions in hooks
For the use function in hooks for example useEffect, my suggestion is defining function inside useEffect, if you're worried about DRY, make your function pure call it in hook and give your params to it.
What about hooks deps? You should/could add all of your params to hooks deps, but useEffect just needs deps which should affect for them changes.
We can use the React hook useCallback as below in a functional component:
const home = (props) => {
const { small, img } = props
const [currentInd, setCurrentInd] = useState(0);
const imgArrayLength = img.length - 1;
useEffect(() => {
let id = setInterval(() => {
if (currentInd < imgArrayLength) {
setCurrentInd(currentInd => currentInd + 1)
}
else {
setCurrentInd(0)
}
}, 5000);
return () => clearInterval(id);
}, [currentInd]);
const onLeftClickHandler = useCallback(
() => {
if (currentInd === 0) {
}
else {
setCurrentInd(currentInd => currentInd - 1)
}
},
[currentInd],
);
const onRightClickHandler = useCallback(
() => {
if (currentInd < imgArrayLength) {
setCurrentInd(currentInd => currentInd + 1)
}
else {
}
},
[currentInd],
);
return (
<Wrapper img={img[currentInd]}>
<LeftSliderArrow className={currentInd > 0 ? "red" : 'no-red'} onClick={onLeftClickHandler}>
<img src={Icon_dir + "chevron_left_light.png"}></img>
</LeftSliderArrow>
<RightSliderArrow className={currentInd < imgArrayLength ? "red" : 'no-red'} onClick={onRightClickHandler}>
<img src={Icon_dir + "chevron_right_light.png"}></img>
</RightSliderArrow>
</Wrapper>);
}
export default home;
I'm getting 'img' from it's parent and that is an array.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
const a = () => {
setCount(count + 1);
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={a}>Click me</button>
</div>
);
}
export default Example;
I'm trying to use React.js component without JSX and receive such warning:
Warning: Something is calling a React component directly. Use a factory or JSX instead. See: http://fb.me/react-legacyfactory
I've visited link but suggested createFactory solution didn't help me :/
app.js
var React = require('react/addons');
var TagsInput = React.createFactory(require('./tagsinput')); // no luck
var TagsComponent = React.createClass({
displayName: "TagsComponent",
saveTags: function () {
console.log('tags: ', this.refs.tags.getTags().join(', '));
},
render: function () {
return (
React.createElement("div", null,
React.createElement(TagsInput, {ref: "tags", tags: ["tag1", "tag2"]}),
React.createElement("button", {onClick: this.saveTags}, "Save")
)
);
}
});
React.render(React.createElement(TagsComponent, null), document.getElementById('tags'));
tagsinput.js
https://raw.githubusercontent.com/olahol/react-tagsinput/master/react-tagsinput.js
I cannot figure out what is the problem here?
React.createClass(spec) returns a component.
React.createElement(component, props, ...children) creates an element.
React.createFactory(component) returns a factory function, which can be used to create an element.
React.createFactory(a)(b, c, d) is the same as React.createElement(a, b, c, d).
You get the warning when you call a component directly, like component(). If you want to call it like a function, use createFactory
var factory = React.createFactory(component);
var element = factory(props, ...children);
Or use createElement:
var element = React.createElement(component, props, ...children);
In 0.13 this will give an error instead of a warning:
var element = component(props, ...children);
Also because React.DOM is going away, you should create dom elements the same way you create component based elements
Edit: looks like React.DOM is sticking around for now.
var div = React.createFactory('div');
var element = div(props, ...children);
// or
var element = React.createElement('div', props, ...children);
Bold used to show consistent terms. ...children means any number of child arguments
You need to wrap all of your child components in createFactory as well, I was able to get your code to run without that specific warning by wrapping Tag and Input in createFactory.
jsbin
For me. The culprit is recompose. I want to convert my functional component to pure. Then I solved it by using memo.
Using memo from react:
import React, { memo } from 'react';
const Component = (props) {
return (
// Component code
)
}
// Wrap component using "memo" HOC
export default memo(Component);
Using pure from recompose:
import React from 'react';
import { pure } from 'recompose';
const Component = (props) {
return (
// Component code
)
}
// Wrap component using "pure" HOC
export default pure(Component);