8

I have a question regarding "one time actions" in react components. Imagine for example I want to scroll some element to certain position, or reset the internal react state.

So far I've been doing this by using a combination of a boolean flag (e.g. doAction: true) and an update action (e.g. setDoActionBackToFalse), but this seems too complex. Does anyone have any nice solution to this?

Note: The action can actually happen multiple times during the lifetime of the component but each time it has to be specifically triggered and happen only once (not keep happening on every rerender). E.g. scroll to every newly added item in scrollpane.

I created small fiddle to make the problem more obvious: https://jsfiddle.net/martinkadlec/et74rkLk/1/ This uses the boolean flag approach.

3
  • constructor() ? Mar 20, 2017 at 10:13
  • After your comments and question update I'm not sure if I understand your problem. If you want to call an action only once when for example you add new item to the list you can just call your action inside method that adds this item...it will not be called on every re-render but only when the method that adds item is called. Mar 20, 2017 at 12:27
  • Well, the function that adds the new item is actually in model, but I need to react to it also in the react component (because thats where I have access to the actual dom elements). Now, the component gets updated with the new list of items in props, but I don't want to do some difficult compares in lifecycle methods to determine new item was added so instead I would prefer to just let the component somehow know that it needs to scroll to the item afterwards. Mar 20, 2017 at 12:33

3 Answers 3

3

It has been some time since I asked this question and since then I found that as long as the "one time action" doesn't actually rerender the component, but instead just modifies some browser state (e.g. focus, scroll position, etc.) people generally tend to solve this by having a class method and calling it from the parent component using refs.

To illustrate on the focus example:

class Input extends React.Component {
  inputElRef = React.createRef();
  focus = () => this.inputElRef.current.focus();
  render() {
    return (
      <input ref={this.inputElRef} />
    );
  }
}

class Parent extends React.Component {
  inputRef = React.createRef();
  render() {
    return (
      <div>
        <button onClick={() => this.inputRef.current.focus()}>Focus input</button>
        <Input ref={this.inputRef} />
      </div>
     );
  }
}
0

I think that you can use componentDidMount lifecycle hook. This hook is invoked only once immediately after a component is mounted and the DOM can be accessed in it.

You can also call your 'one time action' in component constructor but it's called before component is mounted and before initial render so you can't access DOM there.

So you can initialize component state in a constructor (according to React docs: constructor is the right place to initialize state) but you can't scroll some element to certain position in constructor because you can't access component DOM elements in it.

Summing up: state initialization should be done in constructor while 'one time actions' manipulating DOM should be done in componentDidMount.

1
  • Well, the problem isn't really where to call the 'one time action' but rather how to get it to the component in the first place. Usually the action will happen sometimes during the lifetime of the component when someone dispatches it so you will want to react to it in of of the life cycle hooks anyway. Mar 20, 2017 at 12:11
-1

Wrap your action handlers inside a higher order function which invokes them only once. Lodash has once. Ramda has it too.

Updates for your scrolling scenario.... Scrolling is a side effect which must be initiated by the DOM API. You can write an HOC which wraps any component inside it -

   function OnFocusExtender(Wrapped){
       return class ExtendedFocus{
            focus = _.once(elem => elem && elem.focus && elem.focus());
            render(){
                return <Wrapped ref={this.focus} {...this.props} />;
            }
       }
   }

Then you can use it in your code like -

   render(){
       let FocusedComponent = FocusExtender(YourComponent);
       return <FocusedComponent a={"blah"} b={blah} />
   }

Updated for a generic side-effects approach:

The HOC:

   function WelcomingParty(...party)=>(Wrapped)=>{
        return class ExtendWelcome{
            // Every host in the welcoming party greets
            // the guest :)
            welcome = (ref) => party.forEach(host => host(ref));
            render(){
                return <Wrapped ref={this.welcome} {...this.props} />;
            }
        }
   }

Usage:

   let hostFn = (fn)=>(ref)=> ref && (typeof ref[fn] == "function") && ref[fn](),
   hosts = ["focus", "scrollIntoView"].map(hostFn);
   render(){
       let Component = WelcomingParty(...hosts)(YourComponent);
       return <Component a={"blah"} b={blah} />
   }
2
  • This may be going in the right direction but I still have hard time to imagine how it would work. I call it 'one time action' but it can really happen multiple times, its just that it has to be triggered every time. For example imagine that I have an ordered list of items in scrollable element and every time I add new item I want to scroll to it. How exactly would you use the HOC to achieve that? Mar 20, 2017 at 12:15
  • Hm, I guess this would work even for the scrolling. I would just have to create new "once" function every time I want the scrollpane to scroll to new position and pass it trough props. Thanks for the answer. I will wait for a while if perhaps someone else has another interesting completely different approach. Mar 20, 2017 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.